with的用法以及在命名空间上的用法和简化对象document.的用法

  <script>
 
 var obj={
     
     
   name:"obj"
 }
 var name='window';
 var age=18
 function test(){
     
     
   var name='scope';
   with(obj){
     
     
     var age=17
     //with可以改变作用域链,它能让作用域链的最顶端变成with括号里面的对象 找它的AO
     console.log(name);//打印的是obj的name
     console.log(age);//obj里没有age
   }
 }
 test()
  </script>

在命名空间上的用法

<script>
 
   var obj={
     
     
     dp1:{
     
     
       a:{
     
     
         name:"aaa"
       },
       b:{
     
     
         name:"bbb"
       }
     },
     dp2:{
     
     
       c:{
     
     
         name:"cccc"
       }
     }
   }
   with(obj.dp1.a){
     
     
     console.log(name);
   }
   with(obj.dp2.c){
     
     
     console.log(name);
   }

  </script>

简化document.用法
比如我们在用document.write的时候,写代码很麻烦,也可使用with

 <script>
  var a=10
   with(document){
     
     
     write(a)
   }

  </script>

缺点,with改的是作用域链,系统内核消耗效率去改变作用域链,效率很低,所以es5严格模式不准使用with

猜你喜欢

转载自blog.csdn.net/x1037490413/article/details/109031027