简体   繁体   中英

Is it possible to call a function defined inside a closure?

In the following code, I can call baz. Also somewhere else I read "JavaScript has function-level scope". I know, Im confusing myself somewhere. Can somebody make me understand please?

/* An anonymous function used as a closure. */
var baz;
(function() {
    var foo = 10;
    var bar = 2;
    baz = function() { 
        return foo * bar; 
    };
})();

baz(); // baz can access foo and bar, even though it is executed outside of the
       // anonymous function

.

The variable baz is declared outside the anonymous function (even if it isn't actually defined until you use the function expression to assign a value to it). This places its scope outside said function.

foo and bar are declared inside the anonymous function, which limits their scope to that function. The function assigned to baz can access them because they were in scope when it was created.

David explained it pretty well. Things that are in scope where you define baz , are still available after your anonymous function has returned.

Read about closures for more information.

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