我指的是 JavaScript var hoisting
的文档,在一个部分我找到了 Initialization of several variables用Example如下所示。
var x = 0;
function f(){
var x = y = 1;
}
f();
console.log(x, y); // outputs 0, 1
// x is the global one as expected
// y leaked outside of the function, though!
我想得到的异常是 Uncaught Reference Error: y is not defined
。
但由于范围泄漏并没有发生,它正在显示 0,1
。
我能详细知道为什么会这样吗? 最后有任何与性能相关的问题吗?
最佳答案
你没有声明y
。
var x = y = 1;
相当于
y = 1;
var x = y; // actually, the right part is precisely the result of the assignement
安undeclared variable is a global variable (除非你在 strict mode 中,否则这是一个错误)。
你提到的例子是不同的,有一个逗号,is part of the multiple declaration syntax .
你可以修复你的代码
var y=1, x=y;
关于javascript - 为什么初始化多个变量会导致范围泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31428785/