简体   繁体   English

是否可以调用闭包内定义的函数?

[英]Is it possible to call a function defined inside a closure?

In the following code, I can call baz. 在下面的代码中,我可以调用baz。 Also somewhere else I read "JavaScript has function-level scope". 在其他地方,我读到“JavaScript具有功能级范围”。 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). 变量baz在匿名函数之外声明(即使它实际上没有定义,直到你使用函数表达式为它赋值)。 This places its scope outside said function. 这将其范围置于所述函数之外。

foo and bar are declared inside the anonymous function, which limits their scope to that function. foobar在匿名函数中声明,这将其范围限制为该函数。 The function assigned to baz can access them because they were in scope when it was created. 分配给baz的函数可以访问它们,因为它们在创建时在范围内。

David explained it pretty well. 大卫解释得很好。 Things that are in scope where you define baz , are still available after your anonymous function has returned. 在您的匿名函数返回后,仍然可以使用定义baz范围内的内容。

Read about closures for more information. 阅读有关闭包的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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