比较funny……
var variable = "top-level";
function printVariable() {
print("inside printVariable, the variable holds '" +
variable + "'.");
}
function test() {
var variable = "local";
print("inside test, the variable holds '" + variable + "'.");
printVariable();
}
test();
猜猜,结果是啥吧,解释如下:
The variables in this local environment are only visible to the code
inside the function. If this function calls another function, the
newly called function does not see the variables inside the first
function
如果定义的地方换一下:
var variable = "top-level";
function parentFunction() {
var variable = "local";
function childFunction() {
print(variable);
}
childFunction();
}
parentFunction();
结果就不一样了
However, and this is a subtle but extremely useful phenomenon, when a function is defined inside another function, its local environment will be based on the local environment that surrounds it instead of the top-level environment.
以上内容出自:
Eloquent javascript