Home >Web Front-end >JS Tutorial >Detailed explanation of the functions and side effects of the with statement in JavaScript
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; }
Function
document.forms[0].address.valueIf 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 = ''; }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
var o = {x:0}; with(o) x = 1; console.log(o.x);//1If 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
var x = 1; var o = {}; with(o){ x = 2; } console.log(x);//2 console.log(o.x);//undefined
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!