Introduction to Object types in JavaScript
You can create an Object instance in either of the following ways. First, use the new operator followed by the Object constructor, as shown below:
The Code is as follows:
Var person = new Object ();
Person. name = "zxj ";
Person. age = 25;
Another way is to use the object literal representation. Object literal is a short form of object definition. It aims to simplify the process of creating objects with a large number of attributes. The Code is as follows:
The Code is as follows:
// Object literal
Var person = {
Name: "zxj ",
Age: 25
}
When defining an Object using the Object literal, the Object constructor is not actually called.
Generally, the object attribute is accessed in dot notation, but in JavaScript, the object attribute can also be accessed using square brackets notation. When square brackets syntax is used, the attribute to be accessed should be placed in square brackets in the form of a string, as shown below:
The Code is as follows:
Alert (person ["name"]) // zxj
Alert (person. name) // zxj
There is no difference between the two functions, but the main advantage of the square brackets syntax is that attributes can be accessed through variables:
The Code is as follows:
Var propertyName = "name ";
Alert (person [propertyName]); // zxj
If the attribute name contains characters that may cause syntax errors, or the attribute name uses keywords or reserved words, you can also use square brackets. For example:
The Code is as follows:
Person ['first name'] = "zxj ";