Home > Article > Web Front-end > How to use with in javascript
In JavaScript, with is used to extend the scope chain of a statement. It is usually used as a shortcut to repeatedly reference multiple properties in the same object without repeatedly referencing the object itself; the syntax is "with (expression) {execute statement...}".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Basic usage of javascript with
#The original intention of the with statement is to provide a namespace-style shorthand method for level-by-level object access. Also That is, in the specified code area, the object is called directly through the node name.
The with statement is used to extend the scope chain of a statement. The syntax is as follows:
with (expression) { statement }
expression
Adds the given expression to the scope chain used when evaluating statements. Parentheses around the expression are required.
statement
Any statement. To execute multiple statements, use a block statement ({ ... }) to group the statements.
with is usually used as a shortcut to repeatedly reference multiple properties in the same object without repeatedly referencing the object itself.
For example, there is currently an object like this:
var obj = { a: 1, b: 2, c: 3 };
If you want to change the value of each item in obj, the general writing method may be like this:
// 重复写了3次的“obj” obj.a = 2; obj.b = 3; obj.c = 4;
And There will be a simple shortcut by using with writing method
with (obj) { a = 3; b = 4; c = 5; }
In this code, the with statement is used to associate the obj object, which means that inside the with code block, each variable is first Considered as a local variable, if the local variable has the same name as a property of the obj object, then this local variable will point to the property of the obj object.
Disadvantages of with
In the above example, we can see that with can help us simplify the code very well . But why is it not recommended? Let’s talk about the shortcomings of with:
Leads to data leakage
Let’s look at the following part of the code
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); //underfined console.log(a); //2,a被泄漏到全局作用域上
First, let’s analyze the code above. In the example, two objects o1 and o2 are created. One of them has the a attribute, the other one does not. foo(obj)
The function accepts a formal parameter of obj, which is an object reference, and executes with(obj) {...}
on the object reference. Inside the with block, there is a lexical reference to a, which is actually an LHS reference, and 2 is assigned to it.
When we pass o1 in, a = 2
The assignment operation finds o1.a and assigns 2 to it. When o2 is passed in, o2 does not have a property, so this property will not be created, and o2.a remains undefined.
But why does the operation of o2 lead to data leakage?
Here we need to return to the mechanism of LHS query
.
When we pass o2 to with, the scope declared by with is o2, and LHS query
is performed on a starting from this scope. The identifier a is not found in the scope of o2, the scope of foo(…) and the global scope, so in non-strict mode, a global variable will be automatically created in the global scope), in Strict mode will throw a ReferenceError
exception.
Another reason why with is not recommended is. In strict mode, with is completely prohibited, as are indirect or unsafe uses of eval(…).
Performance degradation
with modifies or creates new scopes at runtime to fool other lexical scopes defined at write time. with can make the code more scalable. Although there is the possibility of data leakage above, it can be avoided with a little attention. Isn't it possible to create good functions?
The answer is no. Let’s look at the following part of the code for the specific reasons.
The following code can be copied and run directly
<script> 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"); } func(); 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"); } funcWith(); </script>
Then, the test effect:
In processing the same In the logical code, the running time without using with is only 4.63 ms. The usage time of using with is as long as 81.87ms.
Why is this?
The reason is that the JavaScript engine will perform several performance optimizations during the compilation phase. Some of these optimizations rely on being able to statically analyze the code based on its lexicon and predetermine where all variables and functions are defined so that identifiers can be found quickly during execution.
But if the engine finds with in the code, it can simply assume that any judgment about the position of the identifier is invalid, because there is no way to know the object passed to with to create the new lexical scope. What exactly is the content.
The most pessimistic situation is that if with appears, all optimizations may be meaningless. Therefore, the simplest approach the engine will take is to not do any optimization at all. If the code uses a lot of with or eval(), it will definitely run very slowly. No matter how clever the engine is in trying to minimize the side effects of these pessimistic scenarios, it cannot avoid the fact that without these optimizations, the code will run slower .
【Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of How to use with in javascript. For more information, please follow other related articles on the PHP Chinese website!