Understanding the with keyword in javascript, javascriptwith
When talking about the with keyword in Javascript, the first impression of many friends may be that the with keyword is used to change the scope. The most important thing is that the with keyword is not recommended. When we hear that the with keyword is not recommended, many of us will ignore the with keyword and think it is enough to ignore it. But sometimes, when we look at some code or interview questions, there will be problems related to the with keyword, many pitfalls you have never touched, so it is necessary to talk about the with keyword.
I. Basic description
In js advanced programming, the with keyword is described as follows: The with statement is used to set the code scope to a specific scope. The basic syntax is as follows:
with (expression) statement;
The with keyword is used to simplify writing multiple times to access the same object. For example:
var qs = location.search.substring(1);var hostName = location.hostname;var url = location.href;
These lines of code access the properties in the location object. If the with keyword is used, the code can be simplified as follows:
with (location){ var qs = search.substring(1); var hostName = hostname; var url = href;}
In this Code, the with statement is used to associate the location object. This means that within the with code block, each variable is considered a local variable first, if the local variable has the same name as a property of the location object, the local variable points to the property of the location object.
Note: you cannot use the with statement in strict mode.
Ii. disadvantages of the with Keyword
In the preceding basic description, we can see that one of the functions of with is to simplify the code. But why is it not recommended? The following describes the disadvantages of:
1. performance problems
2. Unclear semantics and difficult debugging
Iii. performance problems
First, let's talk about the performance problem. For the performance problem of using the with keyword, let's take a look at two sections of code:
The first code does not use 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 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 the with keyword is used, the code performance is greatly reduced. The with statement of the second Code applies to the obj2 object, and then the with block accesses the obj object. One idea is that when the with keyword is used to access the variable in the with block, the system first searches for the attribute named obj on obj2. If not, the system proceeds to the next search, this process causes performance degradation. But is the reason why the program performance actually decreases?
Modify the second Code 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 applies the with statement to the obj object, and then directly uses a to access the attribute of obj. According to the previous point of view, when accessing the attribute, this attribute can be found on obj at one time, but why is the code performance still decreasing.
The real reason is: after the with keyword is used, the JS engine cannot optimize this code.
The JS engine has a compilation phase before code execution. When the with keyword is not used, the js engine knows that a is an attribute on obj, it can analyze the code statically to enhance the identifier resolution, thus optimizing the code, so the code execution efficiency is improved. After the with keyword is used, the js engine cannot determine whether a variable is a local variable or an attribute of obj. Therefore, when the js engine encounters the with keyword, it will give up optimization on this 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 the code, which is also a factor affecting performance.
Iv. Unclear semantics, difficult to debug
As mentioned above, in addition to performance issues, with still has a drawback that the semantics is unclear and difficult to debug, which is to make the code hard 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); // 2foo(o2);console.log( o2.a ); // undefinedconsole.log( a ); // 2
This code is easy to understand. In the foo function, the with keyword is used to access the passed obj object, and then the attribute is modified. When the o1 object is passed in, there is no problem because the o1 object has the attribute. When an o2 object is passed in, when the attribute is modified, the modified a attribute becomes a global variable because the o2 object does not have the attribute. This leads to potential bugs.
5. Extended analysis
As mentioned above, I believe you have understood why the with keyword is not recommended and possible problems. Let's take a look at some more complex situations and look at the following code:
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, outputs 30, 20, and undefined respectively. There are also many knowledge points involved: the with keyword, this keyword, variable escalation, and so on. Let's explain them one by one.
1. this keyword
There are quite a few articles on the this keyword google. We will not repeat it here. We just need to remember that the keyword this always points to the object that calls the function. In the foo function, this points to the obj object. Therefore, in the with (this) Statement block, you can directly access the x attribute of obj through the x variable.
2. Variable increase
Variable upgrading in js is also a common 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:
Var obj = {x: 10, foo: function () {var x; // declare the local variable x var y; // declare the local variable y with (obj) {x = 20; // access variable x. If x is found on obj, it is changed to 20 y = 30; // access variable y, which cannot be found on bojg, find the local variable y and change it to 30 console. log (y); // 30 // directly output the local variable y, }}}; obj. foo (); console. log (obj. x); // 20, obj. x has been changed to 20console. log (obj. y); // undefined. If obj does not have the y attribute, It is undefined.
The above comments explain the code execution process. I believe you have understood why the source is, and undefined.
If you are interested, you can refer to the following code:
({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 will this code output? Why?
Summary
This article summarizes the features and disadvantages of the with statement. In general, it is strongly not recommended to use the with keyword. In fact, in daily coding, we only need to know that we do not use with, but sometimes we may encounter some strange problems about with, and want to find out the real reasons, it is necessary to have a deep understanding of the with keyword, which helps us to learn more about the JS language and is also a pleasure to learn about JS.
Articles you may be interested in:
- Cross-frame variable reference using the "with" statement in js
- Js with statement usage
- Simplified with coding in javascript
- How to Use the with statement in JavaScript
- With
- Several implementation methods of startWith and endWith in javascript
- Two Methods for customizing startWith () and endWith () in javascript
- Syntax format and usage of the with () method in javascript
- Examples of with function usage in javaScript
- Implementation of the String. startsWith and endsWith methods in Javascript