JavaScript 'hoisting'
我遇到了javascript"提升",但我不知道这段代码是如何真正起作用的:
1 2 3 4 5 6 7 8 9 10 11 | var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a); |
我知道像(
这是因为本例中的编译/解释顺序有些误导。
您可以通过将
(1) JavaScript does not have block statement scope; rather, it will be local to the code that the block resides within.
(2) Javascript's declaration of variables in a function scope, meaning that variables declared in a function are available anywhere in that function, even before they are assigned a value.
(3) Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable.
您的代码与:(阅读评论)
1 2 3 4 5 6 7 | var a = 1; //global a = 1 function b() { a = 10; var a = 20; //local a = 20 } b(); alert(a); //global a = 1 |
参考文献:(1)javascript变量范围:(2)javascript提升的危险示例(3)变量范围
所以在你的代码中:
1 2 3 4 5 6 7 8 | var a = 1; //global a = 1 function b() { a = 10; return; function a() {} //local } b(); alert(a); //global a = 1 |
因此,全局变量的值保持不变,您将收到警报1
当我读到你做了javascript范围界定和提升的同一篇文章时,我也感到困惑,因为作者从未展示编译器中解释的两个开放示例代码。
下面是您提供的示例,第二页是:
1 2 3 4 5 6 7 8 | var a = 1; function b() { function a() {} // declares 'a' as a function, which is always local a = 10; return; } b(); alert(a); |
下面是页面上的第一个示例:
1 2 3 4 5 6 7 8 9 | var foo = 1; function bar() { var foo; // a new local 'foo' variable if (!foo) { foo = 10; } alert(foo); } bar(); |
希望这有帮助