[英]Variable Scope in Closure
In the following code (from Secrets of the JavaScript Ninja ), I don't understand why inner | tooLate
在下面的代码中(来自JavaScript Ninja的秘密 ),我不明白为什么
inner | tooLate
inner | tooLate
prints out ronin
. inner | tooLate
打印ronin
。 I would've expected undefined
. 我希望
undefined
。
var outerValue = "ninja";
var later;
function outerFunction() {
var innerValue = "samurai";
function innerFunction(paramValue) {
console.log("outerValue:",outerValue);
console.log("innerValue:",innerValue);
console.log("paramValue:",paramValue);
console.log("inner | tooLate", tooLate);
}
later = innerFunction;
}
console.log("outer | tooLate", tooLate);
var tooLate = "ronin";
outerFunction();
later("warrior");
My confusion is how tooLate
is accessible within innerFunction
. 我的困惑是如何在
tooLate
中访问innerFunction
。 Isn't innerFunction
's scope limited to outerFunction
? innerFunction
的范围不限于outerFunction
吗?
innerFunction
is under outerFunction
which is under window
, therefore innerFunction
can access all properties and methods of window
. innerFunction
位于window
下的outerFunction
下,因此innerFunction
可以访问window
所有属性和方法。
In your example, tooLate
is declared under the window
scope (global). 在您的示例中,在
window
范围(全局)下声明了tooLate
。 Since you haven't declare a new tooLate
in outerFunction
nor innerFunction
, it will trace back all the way to window
to find a declared tooLate
. 由于您尚未在
outerFunction
和innerFunction
声明新的tooLate
,因此它将追溯到window
以查找声明的tooLate
。
var b, val = 0;
function a(){
b = function (){
console.log(val);
}
}
a();
val = 2;
b(); //2
Scope:
window
├─ a: function
│ └─ b: function b can access variables in a, b, and all the way to window
└─ val: number if the variable name hasn't been overridden
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.