With keyword in javascript

Source: Internet
Author: User

Talking about the WITH keyword in JS, the first impression of many small partners may be that the WITH keyword is used to change the scope, and then the most critical point is not recommended using the WITH keyword. When you hear that the WITH keyword is not recommended, many of us will ignore the WITH keyword and think it is OK to leave it alone. But sometimes, when we look at some code or interview questions, there are related questions about the WITH keyword, many pits are not contacted by you, so it is necessary to say with this keyword. Basic Description

In JS advanced programming This describes the WITH keyword: the action of the WITH statement is to set the scope of the code to a specific scope, the basic syntax is as follows:

With (expression) statement;
The use with keyword is intended to simplify the work of accessing the same object multiple times, such as the following example:

var qs = location.search.substring (1);
var hostName = location.hostname;
var url = location.href;
These lines of code are access to the properties in the Location object, and if you use the WITH keyword, you can simplify the code as follows:
With (location) {

    var qs = search.substring (1);

    var hostName = hostName;

    var url = href;

}
In this code, the location object is associated with the WITH statement, which means that within the with code block, each variable is first considered a local variable, and if the local variable has the same name as a property of the Location object, the local variable points to the Location object property.
Note: You cannot use the WITH statement in strict mode. with the disadvantages of the keyword

In the previous basic description, we can see that one of the functions of with is to simplify the code. But why not recommend it. Here's what we say with the disadvantages of:
1, Performance problems
2, semantic ambiguity, debugging difficulties
Performance Issues

To start with the performance problem, for the performance problem with the WITH keyword, let's look at two pieces of code first:
The first piece of code is not using the WITH keyword:

function func () {

    console.time ("func");

    var obj = {

        A: [1, 2, 3]

    };


    for (var i = 0; i < 100000; i++) {
        var v = obj.a[0];
    }

    Console.timeend ("func");//0.847ms
}

func ();
The second paragraph code uses the WITH keyword:
function Funcwith () {

    console.time ("Funcwith");

    var obj = {

        A: [1, 2, 3]

    };

    var obj2 = {X:2};

    With (OBJ2) {

        console.log (x);

        for (var i = 0; i < 100000; i++) {

            var v = obj.a[0];

        }
    }

    Console.timeend ("Funcwith");//84.808ms

}

funcwith ();
After using the WITH keyword, the performance of the code has been significantly reduced. The WITH statement of the second Code acts on the Obj2 object, and then the With block accesses the Obj object. One idea is that when you use the WITH keyword to access a variable in a with block, you first find the attribute on the obj2 that is named obj, and if not, the next step, which results in a decrease in performance. But is it really the reason that the performance of the program is actually reduced?
Let's revise the second code and modify it as follows:
function Funcwith () {

    console.time ("Funcwith");

    var obj = {

        A: [1, 2, 3]

    };

    With (obj) {for

        (var i = 0; i < 100000 i++) {

            var v = a[0];

        }

    }

    Console.timeend ("Funcwith");//88.260ms

}

funcwith ();
This code uses the WITH statement on the Obj object, and then directly using a to access the A attribute of obj, which, according to the previous view, can be found on obj at one time, but why the code performance is still reduced.
The real reason: After using the WITH keyword, the JS engine is unable to optimize the code.
JS engine before code execution has a compile phase, when not using the WITH keyword, the JS engine knows that a is a property on obj, it can statically analyze the code to enhance the resolution of identifiers, thus optimizing the code, so the efficiency of code execution increased. Using the WITH keyword, the JS engine cannot tell whether a variable is a local variable or an attribute of obj, so the JS engine, after encountering the WITH keyword, discards the optimization of the code, so the execution efficiency is reduced.
The effect of using the WITH keyword on performance is also the JS compression tool, which cannot compress this code, which is also a factor affecting performance.
ambiguous semantics, difficult to debug

In addition to the performance of the problem, with the existence of a shortcoming of the semantic ambiguity, difficult to debug, is caused by the code is not easy to read, and may cause potential bugs.

function foo (obj) {with

    (obj) {

        a = 2;

    }

}

var O1 = {

    a:3

};

var O2 = {

    b:3

};

Foo (O1);
Console.log (o1.a); 2

foo (O2);
Console.log (o2.a); Undefined
console.log (a);//2
This code is easy to understand, in the Foo function, using the WITH keyword to access the incoming Obj object, and then modify the A property. This is no problem when the O1 object is passed in because the O1 object has a property. When the O2 object is passed in, when the A property is modified, the modified a property becomes a global variable because the O2 object does not have a property. This creates a potential bug.
Extension Analysis

As I have said before, I believe you have understood why the WITH keyword and possible problems are not recommended. Let's take a look at some of the more complex situations and look at the following code:

var obj = {
    x:10,
    foo:function () {with

        (this) {

            var x =;
            var y =;

            Console.log (y);//30
        }
    }
;

Obj.foo ();
Console.log (obj.x);//20
Console.log (OBJ.Y);//undefined
In this code, output the 30,20,undefined separately. The knowledge points involved are also more: With the keyword, this keyword, variable elevation and so on, we come to one by one to explain.
1. This keyword
The article on this keyword is quite a bit more than Google, and here we will just remember one point: this keyword always points to the object that calls the function. Here, in the Foo function, this refers to the Obj object. Therefore, in the WITH (this) statement block, you can access the X property of obj directly through the x variable.
2. Variable elevation
JS in the variable ascension is also a frequent problem, we can simply understand that in JS, the variable declaration will be promoted to the top of the function, although sometimes it is declared later.
So the above code can be resolved to:
var obj = {
    x:10,
    foo:function () {
        var x;//declares local variable x
        var y;//declares local variable y
        with (obj) {
            x = 20;//access variable x, Find x on obj, then modify to
            y = 30;//access variable y, find y on obj, further find, find local variable y, modify to
            Console.log (y),//30//Direct output local variable y,
        }
    }
};

Obj.foo ();
Console.log (obj.x);//20,obj.x has been modified to
Console.log (OBJ.Y);//undefined,obj does not exist Y property; undefined
The comments above explain the execution of the code, and I believe you have understood why the source is 30,20,undefined.
Interested students can take a look at the following code:
({
    x:10,
    foo:function () {
        function bar () {
            console.log (x));
            Console.log (y);
            Console.log (this.x);
        }

        With (this) {
            var x =;
            var y =;

            Bar.call (this);}}
). Foo ();
What this piece of code will output. Why, then?
Summary

This paper summarizes the features and drawbacks of the with statement, in general, strongly deprecated with the keyword. In fact, in the daily coding, we just need to know not to use with on it, but sometimes we may encounter some strange questions about with, want to find out the real reason, it is necessary to understand the WITH keyword, which helps us to in-depth learning JS this language, It is also a fun to learn JS. Welcome small friends to exchange.

Reprint Address: http://www.cnblogs.com/lrzw32/p/5189450.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.