当前位置: 代码迷 >> 综合 >> with语句的本质
  详细解决方案

with语句的本质

热度:27   发布时间:2024-01-16 15:36:45.0
通过测试及debug后, 得出结论, 仅代表个人意见:

with的本质, 就是构造一个作用域, 将with的对象的所有key, 声明为局部变量




var inner = '123';
var outer = {inner : 'hello world', another: 'hello with'};
window.obj = {outer: outer};

with(outer) {
alert(inner);
alert(another);
alert(outer.inner);
alert(window.obj.outer.inner);
show();
}


function show() {
alert(inner);

}


等同于以下代码



var inner = '123';
var outer = {inner : 'hello world', another: 'hello with'};
window.obj = {outer: outer};

(function(inner, another) {
alert(inner);
alert(another);
alert(outer.inner);
alert(window.obj.outer.inner);
show();
})(outer.inner, outer.another);


function show() {
alert(inner);

}




再看看下面这个常见的问题, 一目了然
[code]
var root = {
branch: {
node: 1
}
};

with(root.branch) {
root.branch = {
node: 0
};
// 显示 1, 错误!
alert(node);
}
// 显示 0, 正确!
alert(root.branch.node);
[/code]
  相关解决方案