This article mainly introduces the Object type in JavaScript. This article describes two methods for creating the Object type and how to access the Object type, you can refer to the following two methods to create an Object instance. 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 ";
We recommend that you use dot notation unless square brackets are required.