({
x: 10,
foo: function () {
function bar() {
console.log(x);
console.log(y);
console.log(this.x);
}
with (this) {
var x = 20;
var y = 30;
bar.call(this);
}
}
}).foo();
上面的代码是 http://dmitrysoshnikov.com/ecmascript/the-quiz/ 中的第九题,
请问为什么console.log(x)输出undefined
声明提升
var声明会被提升到函数作用域顶部,方法可以改写为
with作用域
在with作用域里寻找变量的时候先去with对象里找,找不到时按照正常的闭包的方式找,见下注释(注意注释前的数字顺序)