1)此警报的原因1是因为即使您test()事先调用了该函数,它本身也在调用并创建自己的闭包并在其中声明一个单独var example = 2;的内部。(所以你的警报看不到它,它只看到1)。现在,如果您这样做了:return example = 2;您会注意到 alert(example) === 2。这是因为您将示例从闭包中取出,并且它影响了前面的示例变量。
example = 1;
function test(){
var example = 2;
}
test();
alert(example);
2)在这里,您没有在函数内部创建新变量,因此它能够(通过闭包)访问它外部的变量示例,并将其更改为 2。
example = 1;
function test(){
example = 2;
}
test();
alert(example); //alert 2 no matter if example=1 or var example=1 before function
3)最后一个是“关闭”如何在这里工作的一个很好的例子。变量,不像我们说function ()必须在试图访问它们的东西之上声明。另一方面,函数没有。所以虽然var example = 1可能低于function test() { }自身,但没关系。重要的是它在CALL to之前声明test()。这是创建闭包的时候,它将自己包裹在它可以看到/访问的任何变量等周围。
// so this ...
var example = 1;
function test(){
alert(example);
}
// and this work ...
function test(){
alert(example);
}
var example = 1; // <-- notice it's still above the test() func call, it can still see example
test(); //always alert 1, no matter if var example=1 or example=1 before function
// if var example = 1; was down here below it, it would alert "undefined", this is because
// the variable was not available within the scope when test() was called.