JavaScript has a with keyword, and the WITH statement is intended to provide a namespace-style sketch for hierarchical object access. That is, in the specified code area, the object is invoked directly through the node name.
The action of the WITH statement is to temporarily change the scope chain and reduce the repeated input.
Its grammatical structure is:
With (object) {
//statements
Give me a practical example:
With (document.forms[]) {
name.value = "Lee King";
Address.value = "Peking";
Zipcode.value = "";
The corresponding traditional wording is:
Document.forms[].name.value = "Lee King";
Document.forms[].address.value = "Peking";
Document.forms[].zipcode.value = "";
You can see the simplicity of the WITH statement, but it's hard to find true perfection in the world of code.
The JS interpreter needs to check whether the variable in the With block belongs to the with contained object, which will cause the WITH statement to execute greatly, and cause the JS statement to be difficult to optimize. To balance the speed and the amount of code you can find a more eclectic solution:
var form = document.forms[];
Form.name.value = "Lee King";
Form.address.value = "Peking";
Therefore, we should avoid using the WITH statement as much as possible in future efficient code development.
After testing:
var a = 123;
var B = {a:321};
With (b) {
console.log (a);//321
}
var a = 123;
var b = {}; This removes the A attribute in B with
(b) {
console.log (a);//123
In JavaScript, a function is also an object, in fact, everything in JavaScript is an object. Inside a function is an internal property that is only accessible to the JavaScript engine, which contains a collection of objects in the scope of the function when it was created, which is called the scope chain.
For example, the following code:
function Add (num1,num2) {
var sum = num1 + num2;
return sum;
When a function is created, its scope chain fills in a global object that contains all the global variables, as shown in the following figure:
When the function is executed, an active object is created that contains all the local variables of the function, named arguments, and this, and then the object is pushed into the front of the scope chain, and the object is destroyed as soon as the function finishes executing.
As you can see, global variables are pushed to the end of the scope chain by the active object, which is why global variables are slow to access!
With
In general, the scope chain is only affected by the with and catch statements. When you make the creation with with, the function creates a new active object, pushing it to the front end, which is the object of the With. This means that all local variables are in the second scope chain object, which is why you should avoid using with.
The above is a small set to introduce the JavaScript with the statement of the understanding, hope to help everyone, if you want to learn more information please pay attention to cloud Habitat community website!