这是一道面试题!我也不知道其中的原因!
function fun(val) {
this.x = val;
return this;
}
var x = fun(1);
var y = fun(2);
console.log(x.x); //I can't understand this result.
console.log(y.x);
最佳答案
嗯,我认为发生这种情况是因为 fun 函数中的“This”指的是 Window 对象,而不是函数内的本地对象。因此,您首先通过 fun(1) 调用它并使 window.x = 1,然后通过 fun(2) 调用它,它变为 window.x = 2 .. 然后当 x 和 y 都为对 window 的引用...因此两者将具有相同的最终值。
关于javascript - 面试测试关于javascript中的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762364/