Now describes how to add, modify, or delete properties and methods for an object. In other languages, once an object is generated, it cannot be changed, and adding a modified member to an object must be modified and instantiated in the corresponding class, and the program must be recompiled. This is not true of JavaScript, it provides a flexible mechanism to modify the behavior of objects, you can dynamically add, modify, delete properties and methods. For example, use class object first to create an empty object user:
var user=new Object ();
1. Add properties
The user object does not have any properties or methods, apparently for no purpose. However, you can add properties and methods to it dynamically, for example:
User.name= "Jack";
user.age=21;
user.sex= "Male";
With the above statement, the user object has three properties: Name, age, and sex. The following three statements are exported:
alert (User.Name);
alert (user.age);
alert (user.sex);
As the code runs, three properties are already fully owned by the user object.
2. Add method
The procedure and properties for adding a method are similar:
User.alert=function () {
Alert ("My name is:" +this.name);
}
This adds a method "alert" to the user object, and by executing it, you can pop up a dialog box to display your name:
User.alert ();
3. modifying properties
The process of modifying a property is to replace the old attribute with the new one, for example:
User.name= "Tom";
User.alert=function () {
Alert ("Hello," +this.name);
}
This modifies the value of the user Object Name property and the alert method, which is changed from the display "My name is" to show "Hello".
4. Deleting a property
the process of deleting a property is also simple, which is to place it as undefined:
user.name=undefined;
user.alert=undefined;
This deletes the Name property and the alert method. In the following code, these properties become unavailable.
When you add, modify, or delete an attribute, it is the same as a reference property, or you can use the square brackets ([]) syntax:
user["name"]= "Tom";
An additional feature of this approach is that you can use a non-identifier string as the property name, for example,
identifiers are not allowed to start with a number or spaces, but can be used in square brackets ([]) syntax:
user["My Name"]= "Tom";
Note that when you use a property with this non identifier as the name, you still need to refer to the square brackets syntax:
Alert (user["my Name"));
and cannot be written as:
Alert (user.my name);
With this nature of the object, it is even easy to implement a simple hash table, which will be seen in its application later in this book. As you can see, each object in JavaScript is dynamically variable, which gives you a lot of flexibility in programming, and it makes a big difference to other languages, and the reader is able to appreciate that.