Understanding the WITH keyword in javascript

Source: Internet
Author: User

Speaking of JS with the keyword, many small partners first impression may be that the WITH keyword to change the scope, and then the most critical point is not recommended to use the WITH keyword. When we hear the deprecated with keyword, many of us ignore the WITH keyword and think that it's all right to leave it alone. But sometimes, when we look at some code or interview questions, there will be related issues with the keyword, many pits you have not touched, so it is necessary to say with this one keyword.

I. BASIC INSTRUCTIONS

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

?
1 with(expression) statement;

The purpose of using the WITH keyword is to simplify the process of writing access to the same object multiple times, such as the following example:

?
123 varqs = location.search.substring(1);var hostName = location.hostname;varurl = 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:

?
12345 with(location){  var qs = search.substring(1);  var hostName = hostname;  varurl = href;}

In this code, the location object is associated with a 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: The WITH statement cannot be used in strict mode.

Second, with the disadvantages of the keyword

In the basic instructions above, we can see that one of the functions of with is to simplify the code. But why is it not recommended? Let's talk about the disadvantages of with:

1, performance issues
2. Unclear semantics, difficult to debug

Third, performance problems

First of all, for performance issues, for performance issues with the WITH keyword, let's take a look at two pieces of code:

The first paragraph of code is not using the WITH keyword:

?
1234567891011 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 piece of code uses the WITH keyword:

?
123456789101112131415 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 is greatly reduced. The WITH statement of the second code acts on the object Obj2, and then the Obj object is accessed with the block. One idea is that, with the WITH keyword, when you access a variable within a with block, you first look for a property that is named Obj on Obj2, and if not, this process results in a decrease in performance. But is the reason for the real decrease in program performance really?
Let's revise the second code and modify it as follows:

?
12345678910111213 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 accesses the a property of obj directly using a, which, according to the previous point of view, can be found on obj once when accessing the A property, but why the code performance is still reduced.
The real reason: After using the WITH keyword, the JS engine is unable to optimize this piece of code.
The JS engine has a compile phase before the code executes, and when the WITH keyword is not used, the JS engine knows that a is a property on obj, it can statically parse the code to enhance the parsing of the identifier, thus optimizing the code, thus improving the efficiency of the Code execution. After 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 will abandon the optimization to this code after encountering the WITH keyword, 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.

Four, the semantics is unclear, difficult to debug

In addition to the performance of the problem, with the existence of a disadvantage of unknown semantics, difficult to debug, is to make the code difficult to read, and may cause potential bugs.

?
12345678910111213141516171819 function foo(obj) {  with (obj) {    a = 2;  }}var o1 = {  a: 3};var o2 = {  b: 3};foo(o1);console.log(o1.a); // 2foo(o2);console.log( o2.a ); // undefinedconsole.log( a ); // 2

This code is easy to understand, within the Foo function, using the WITH keyword to access the incoming Obj object, and then modify the A property. This is not a problem when the O1 object is passed in because the O1 object has a property. When you pass in an O2 object, when you modify the A property, because the O2 object does not have a property, the modified a property becomes a global variable. This creates a potential bug.

Five, extension analysis

With all that said, I'm sure you understand why the WITH keyword and possible problems are not recommended. Let's take a look at some of the more complicated scenarios and see the following code:

?
12345678910111213 var obj = {  x: 10,  foo: function () {    with (this) {      var x = 20;      var y = 30;      console.log(y);//30    }  }};obj.foo();console.log(obj.x);//20console.log(obj.y);//undefined

In this code, output the 30,20,undefined separately. There are also many points of knowledge involved: With keyword, this keyword, variable promotion, and so on, let's explain one by one.
1. This keyword
Article about this keyword Google quite a bit above, here no longer repeat, we just need to remember one point: the This keyword always points to the object calling the function. Here, in the Foo function, this is pointing to the Obj object. Therefore, the X property of obj can be accessed directly through the x variable in the WITH (this) statement block.
2. Variable Promotion
The variable promotion in JS is also a frequently encountered 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 parsed as:

?
123456789101112131415 var obj = {  x: 10,  foo: function () {    var x;//声明局部变量x    var y;//声明局部变量y    with (obj) {      x = 20;//访问变量x,在obj上找到x,则修改为20      y = 30;//访问变量y,在bojg上找不到y,则进一步查找,找到局部变量y,修改为30      console.log(y);//30//直接输出局部变量y,    }  }};obj.foo();console.log(obj.x);//20,obj.x已被修改为20console.log(obj.y);//undefined,obj不存在y属性,则为undefined

The above comments explain the execution of the code, I believe you have understood why the source of the 30,20,undefined reason.

Interested students can take a look at the following code:

?
123456789101112131415 ({x: 10,foo: function () {  function bar() {    console.log(x);    console.log(y);    console.log(this.x);  }  with (this) {    var x = 20;    var y = 30;    bar.call(this);  }}}).foo();

What does this piece of code output? Why is it?

Summarize

This article summarizes the features and drawbacks of the With statement, which, in general, strongly recommends using the WITH 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 problems with the problem, to find out the real reason, we need to understand in depth with the keyword, which helps us to learn the JS language, It is also a fun to learn JS.

Understanding the WITH keyword in javascript

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.