[英]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. foo
和bar
在匿名函数中声明,这将其范围限制为该函数。 The function assigned to baz
can access them because they were in scope when it was created. 分配给
baz
的函数可以访问它们,因为它们在创建时在范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.