JavaScript中对with语句描写很少,这里记录一下我自己的理解。
如下代码
(function test(){
var aaa='111';
var location = {};
location.bbb = '123';
location.aaa='456';
with(location){
var aaa='222';
console.log(aaa);//先找局部变量var aaa='222';,如果找不到,才去location下的属性下找
bbb = aaa;//同上
}
console.log(location.bbb);
return aaa;
})()
//输出222 222
上述代码对with语句的使用注意要点:
首先,传入with的参数必须为一个对象,否则会出现很多错误。
其次,在with语句中,最接近的环境是test函数环境。
最后,with内部的局部环境查找变量的顺序是,先查找局部环境中的局部变量,如果找不到则从location中查找同名属性,最后才是全局变量