Now introduce how to add, modify or delete attributes and methods to an object. In other languages, once the object is generated, it cannot be changed. To add a modification member to a object, the member must modify it in the corresponding class and re -instance, and the program must be re -compiled. This is not the case in JavaScript. It provides a flexible mechanism to modify the behavior of the object, which can dynamically add, modify, delete attributes and methods. For example, first use the class Object to create an empty object user:
var user = new object ();
1. Add attribute
At this time, the User object had no attributes and methods, obviously there was no use. But you can dynamically add attributes and methods, such as:
user.name = "jack";
user.age = 21;
user.sex = "Male";
Through the above statements, the User object has three attributes: name, Age, and Sex. The following three statements are output:
alert (user.name);
alert (user.age);
alert (user.sex);
It can be seen from the operation effect of the code that the three attributes have completely belonged to the User object.
2. Method of adding
The process of adding methods is similar to attributes:
user.alert = function () {
Alert ("My name is:"+this.name);
}
This adds a method "Alert" to the User object. By executing it, you can pop up a dialog box to show your name:
user.alert ();
3. Modification attribute
The process of modifying a attribute is to replace the old attributes with new attributes, such as:
user.name = "tom";
user.alert = function () {
Alert ("Hello,"+this.Name);
}
In this way, the value and the alert method of the USER object name attribute is modified, and it has changed from showing "My name is" to display "Hello".
4. Delete attribute
The process of deleting a attribute is also very simple, that is, setting it to undefined:
user.name = undefined;
user.alert = undefined;
This deletes the name attribute and the alert method. In subsequent code, these attributes are not available.
When adding, modified or deleted attributes, the same as the reference attribute can also be used in the square bracket ([]) syntax:
user ["name"] = "tom";
There is also an extra characteristic of using this method, that is, you can use non -standard string as the attribute name, such as
The identifier is not allowed to start with a number or a space, but it can be used in the syntax of the square bracket ([]):
user ["my name"] = "tom";
It should be noted that when using this non -identifier as the attribute as the name, it is still necessary to quote with the square bracket syntax:
alert (user ["my name"];
Can't write as:
alert (user.my name);
Using this nature of the object can even easily achieve a simple hash table, which will be seen after the book. It can be seen that each object in JavaScript is dynamic and variable, which brings great flexibility to programming, and it also produces a large difference from other languages. Readers can experience this nature.