[英]Variable Scope in Closure
在下面的代碼中(來自JavaScript Ninja的秘密 ),我不明白為什么inner | tooLate
inner | tooLate
打印ronin
。 我希望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");
我的困惑是如何在tooLate
中訪問innerFunction
。 innerFunction
的范圍不限於outerFunction
嗎?
innerFunction
位於window
下的outerFunction
下,因此innerFunction
可以訪問window
所有屬性和方法。
在您的示例中,在window
范圍(全局)下聲明了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.