JavaScript has a with keyword. the original purpose of the with statement is to provide a namespace-based write Method for hierarchical object access. that is, in the specified code area, the Java and. NET users should be familiar with the concept of the package or namespace. Because of this concept, the code is concise and easy to read. I don't know how to locate the with statement at the beginning of JavaScript design. I personally think there is a certain degree of similarity between them. for example:
The Code is as follows:
Apple. banana. candy. dog. egg. fog. god. huh. index = 0;
DoSomething (apple. banana. candy. dog. egg. fog. god. huh. index );
Use the with statement to write the following code.
The Code is as follows:
With (apple. banana. candy. dog. egg. fog. god. huh ){
C = 0;
DoSomething (index );
}
It looks wonderful, but it has a fatal defect. Let's perform some small tests.
1. Modify the value in the with statement using internal variables.
The Code is as follows:
Var root = {
Branch :{
Node: 1
}
};
With (root. branch ){
Node = 0;
// Display 0, correct!
Alert (node );
}
// Display 0, correct!
Alert (root. branch. node );
2. Modify the value through the object node in the with statement.
The Code is as follows:
Var root = {
Branch :{
Node: 1
}
};
With (root. branch ){
Root. branch. node = 0;
// Display 0, correct!
Alert (node );
}
// Display 0, correct!
Alert (root. branch. node );
After testing 1 and 2, there is no problem at first glance, but... please refer to test 3.
3. Modify the value through the object parent node in the with statement.
The Code is as follows:
Var root = {
Branch :{
Node: 1
}
};
With (root. branch ){
Root. branch = {
Node: 0
};
// Display 1, Error!
Alert (node );
}
// Display 0, correct!
Alert (root. branch. node );
As shown in Test 3 above, after the parent node of the with statement is modified, it is not synchronized to the node itself. that is to say, internal and external values cannot be consistent. this is a hidden bug in the project.
What should we do? Is there another way to accept that long string of sequential access?
There are some methods. We can use an alias to reference the parent node to call the Node object, such:
The Code is as follows:
Var root = {
Branch :{
Node: 1
}
};
Var quote = root. branch;
Quote. node = 0;
// Display 0, correct!
Alert (root. branch. node );
I believe that few people will use the with statement, and many people will not know this keyword. But I think this is a problematic statement and should not be used at all. So write a small article to record it.