我在引用JavaScript的文档var hoisting
,在一节中我发现了几个变量的初始化,下面给出了一个例子.
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!
Run Code Online (Sandbox Code Playgroud)
在哪里我假设得到例外Uncaught Reference Error: y is not defined
.但它没有发生,因为泄露的范围,它正在显示0,1
.
我能否知道为什么会发生这种情况以及是什么导致这种情况发生的.最后任何与性能相关的问题
你没有宣布y
.
var x = y = 1;
Run Code Online (Sandbox Code Playgroud)
相当于
y = 1;
var x = y; // actually, the right part is precisely the result of the assignement
Run Code Online (Sandbox Code Playgroud)
一个未声明的变量是一个全局变量(除非你是严格的模式,那么它是一个错误).
你所指的例子是不同的,有一个逗号,它是多重声明语法的一部分.
你可以修复你的代码
var y=1, x=y;
Run Code Online (Sandbox Code Playgroud)