JavaScript with

with

Action (two points):

  • Changes in the scope chain
<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

Steps: first find obj inside the AO, find test inside the AO, finally found GO.

It will change the scope chain, allowing the bottom of the scope chain with a function inside the code into an object with brackets, that this object serves as the most direct AO function block inside.

with the code inside will execute normal order, but with the brackets but Tim has a target, then it will use that object as the top of the scope chain code to be executed with body, that it will change the scope chain.

  • Simplify the code
<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
  • But through with modifying the scope chain, consume a lot of memory, the efficiency is very slow.
Published 49 original articles · won praise 30 · views 30000 +

Guess you like

Origin blog.csdn.net/Reagan_/article/details/81327565