简体   繁体   中英

What is the function's return value?

Could you please tell me what is Menu in the return statement below (return Menu;) ? Is it a variable (which is not defined) or the name of the inner function ?

var Menu = (function () {
    // A straightforward constructor. 
    function Menu(item_list, total_pages) {
        // The this keyword is mandatory.
        this.items = item_list;
        this.pages = total_pages;
    }
    // Methods
    Menu.prototype.list = function () {
        console.log("Our menu for today:");
        for (var i = 0; i < this.items.length; i++) {
            console.log(this.items[i]);
        }
    };

    return Menu;
}());

Function declarations create a variable, in the scope of the function they are declared in, with a name that is the same as the name of the function itself.

So the return value is the function, which is the same as the value of the Menu variable.

 function return_function() { function foo() { console.log(1); } console.log(foo); var bar = foo; foo = 2; console.log(foo); return bar; } var baz = return_function(); baz(); 

Is it a variable...?

Effectively. It comes from the function declaration:

function Menu(item_list, total_pages) {
    // The this keyword is mandatory.
    this.items = item_list;
    this.pages = total_pages;
}

Function declarations create what the spec calls a "binding" in the current execution context for the scope. It's effectively a variable.

So return Menu; returns the Menu function reference out of the anonymous function, and the outer var Menu = ... assignment assigns it to the Menu variable in the containing scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM