(
The function of the WITH statement is to temporarily change the scope chain and reduce the repeated input.
Its syntax structure is:
JS Code
- With (object) {
- //statements
- }
Let me give you a practical example:
JS Code
- With (Document.forms[0]) {
- Name.value = "Lee King";
- Address.value = "Peking";
- Zipcode.value = "10000";
- }
The traditional notation that corresponds to this is:
JS Code
- Document.forms[0].name.value = "Lee King";
- Document.forms[0].address.value = "Peking";
- Document.forms[0].zipcode.value = "10000";
You can see the simplicity of the WITH statement, but it's hard to find true perfection in the code world.
The JS interpreter needs to check if the variables in the With block belong to the with object, which will make the WITH statement perform much slower and cause the JS statement to be difficult to optimize. To take into account the speed and the amount of code you can find a more eclectic solution:
JS Code
- var form = document.forms[0];
- Form.name.value = "Lee King";
- Form.address.value = "Peking";
- Form.zipcode.value = "10000";
Therefore, we should avoid using the WITH statement as much as possible in future efficient code development. )
1) Brief description
The WITH statement can be conveniently used to refer to an existing property in a particular object, but cannot be used to add properties to an object. To create a new property for an object, you must explicitly refer to the object.
2) syntax format
With (object instance)
{
code block
}
Sometimes, in a program code, I need to use the properties or methods of an object many times, according to the previous wording, all through: Object. property or object. Methods to obtain the properties and methods of the object separately, a bit of a hassle, after learning the With statement, can be implemented in a similar manner as follows:
With (Objinstance)
{
var str = attribute 1;
.....
} removes the hassle of writing object names multiple times.
3) Example
<script language= "JavaScript" >
<!--
Function Lakers () {
THIS.name = "Kobe Bryant";
This.age = "28";
This.gender = "Boy";
}
var people=new Lakers ();
With (people)
{
var str = "Name:" + name + "<br>";
str + = "Age:" + ages + "<br>";
str + = "Gender:" + gender;
document.write (str);
}
-
</script>
The code performs the following effects:
Name: Kobe Bryant
Age: 28
Sex: Boy
How to use JS with statements