在以下代码中(来自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");


我的困惑是如何在tooLate中访问innerFunctioninnerFunction的范围不限于outerFunction吗?

http://jsfiddle.net/6HuaS/

最佳答案

innerFunctionouterFunction下,而在window下,因此innerFunction可以访问window的所有属性和方法。

在您的示例中,tooLatewindow范围(全局)下声明。由于您没有在tooLateouterFunction中声明新的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

09-19 05:07