with
作用(两点):
- 改变作用域链
<script type = "text/javascript">
var obj = {
name : "obj"
}
var name = 'window';
function test(){
var name = "scope";
var age = "123";
with(obj){
console.log(name);
console.log(age);
}
}
test();
</script>
//obj 123
<script type = "text/javascript">
var obj = {
name : "obj"
var age = "123"
}
var name = 'window';
function test(){
var name = "scope";
var age = "123";
with(obj){
console.log(name);
console.log(age);
}
}
test();
</script>
//obj 234
步骤:先找obj里面的AO,再找test里面的AO,最后找GO。
它会改变作用域链,可以让with函数里面的代码的作用域链的最底端变成with括号里面的对象,也就是说这个对象充当了函数块里面的最直接的AO。
with里面的代码会按照正常顺序执行,但是with的括号里面一但添了对象的话,它会把这个对象当做with要执行的代码体的作用域链的最顶端,也就是说它会改变作用域链。
- 简化代码
<script type = "text/javascript">
var obj = {
dp1 : {
xiaozhang : {
name : "abc",
age : 123
},
xiaoli : {
name : "bcd",
age : 234,
}
},
dp2 : {
xioa'wan : {
name : "chong",
age : 22,
},
},
}
with(obj.dp1.xiaozhang){
console.log(name);
console.log(age);
}
</script>
//abc bcd
- 但是通过with修改了作用域链,消耗了大量的内存,效率是很慢的。