The purpose of defining the with statement is mainly to simplify the work of writing the same object multiple times
The with statement adds the object to the head of the scope chain, then executes the statement, and finally The scope chain is restored to its original state
with(object){
statement;
}
Copy after login
Function
## The with statement is usually used when the object nesting level is very deep. to simplify code writing. Essentially, a new lexical scope is created by treating a reference to an object as a scope and the properties of the object as identifiers in the scope.
In client-side javascript, you may use an expression like the following to access elements in an HTML form
document.forms[0].address.value
Copy after login
If this expression appears multiple times in the code, you can use the with statement to access the form object Add to the top level of the scope chain
with(document.forms[0]){
name.value = '';
address.value = '';
emai.value = '';
}
Copy after login
This method reduces a lot of typing, and there is no need to add the document.forms[0] prefix to each property name. This object is temporarily mounted on the scope chain. When JavaScript needs to parse an identifier such as address, it will automatically look for
in this object. [Note] The with statement provides a way to read A shortcut to the properties of an object, but it does not create the properties of an object
If object o has an attribute x, then the following code assigns the value of this property to 1
var o = {x:0};
with(o) x = 1;
console.log(o.x);//1
Copy after login
If o There is no attribute x defined in . The following code is exactly the same as the code x=1 without using the with statement. This is because an LHS query is performed on the variable At the same time, it will also cause difficulty in debugging the code, and compared with the code without using the with statement, it will operate more slowly.
Moreover, if the with statement is improper, it may cause variable leakage and pollute the global situation. Scope situationvar o = {};
with(o) x = 1;
console.log(o.x);//undefined
console.log(x);//1
Copy after login
Strict mode
In strict mode, it is forbidden to use the with statement
var x = 1;
var o = {};
with(o){
x = 2;
}
console.log(x);//2
console.log(o.x);//undefined
Copy after login
The above is the detailed content of Detailed explanation of the functions and side effects of the with statement in JavaScript. For more information, please follow other related articles on the PHP Chinese website!