JS——es5的严格模式(2)es5.0严格模式不让用的东西(with(){})

  1. with(){}
2.	var obj = {
3.	                name : "obj"
4.	            }
5.	            var name = 'window';
6.	            function test(){
7.	                var name = 'scope';
8.	                with(){
9.	                    console.log(name);
10.	                    
11.	                }
12.	            }
13.	            test();

with里面的代码会按照正常的方式去执行,但是如果你在with后面的括号里面放上一个对象的话,他就了不得了,他会把这个对象,当做with要执行的代码体的作用域链的最顶端,也就是说with会改变作用域链,

var obj = {
                name : "obj"
            }
            var name = 'window';
            function test(){
                var name = 'scope';
                with(obj){
                    console.log(name);
                    
                }
            }
            test();

比如你现在站在with里面去访问这个name的话,他最顶端看到的是obj,他会把obj当成他自己最顶端的AO,连在他原来作用域链的最顶端。

所以你这样访问的name是obj吧。

with有一个作用:with可以改变作用域链,他可以让他里面的代码的作用域链的最顶端变成with括号里面的这个对象,也就是这个对象充当了里面代码的最直接的AO。

var obj = {
                name : "obj",
                age : "234"
            }
            var name = 'window';
            function test(){
                var age = "123";
                var name = 'scope';
                with(obj){
                    console.log(name);
                    console.log(age);
                }
            }
            test();

那这个with有啥作用?with能简化代码。

var org = {
                dp1 : {
                    jc : {
                        name : "abc",
                        age : 123
                    },
                    han : {
                        name : "xiaohan",
                        gae : 234
                    }
                },
                dp2 : {

                }
            }
            with(org.dp1.jc){
                console.log(name);
            }
            with(org.dp1.han){
                console.log(name);
            }

比如:

document上面有很多对象的方法,你可以不用输document,直接输document点后面的东西。

但是with的功能太强大了,你该什么都情有可原,但时你改作用域链就不行了,作用域链是经过很复杂的情况生成的结构,作用域链改了之后,系统内核会消耗大量的效率去更改作用域链,是会把程序变得非常慢的。

所以后来es5.0严格模式就说了,既然我升级了,我就要把这个效率提到最高,那么你这个with就不可以再使用了。

"use strict"
            with(document){
                write("a");
            }

严格模式不能包含with模块。

猜你喜欢

转载自blog.csdn.net/hdq1745/article/details/85462885