在下面的代码中(来自Secrets of the JavaScript Ninja),我不明白为什么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");
我的困惑是如何在 innerFunction
中访问 tooLate
。 innerFunction
的范围不是限制在outerFunction
吗?
最佳答案
innerFunction
在 outerFunction
下在 window
下,因此 innerFunction
可以访问 window
的所有属性和方法.
在您的示例中,tooLate
在 window
下声明范围(全局)。由于您尚未声明新的 tooLate
在outerFunction
也不innerFunction
,它会一直追溯到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
关于javascript - 闭包中的变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20865479/