JavaScript-Object type introduction _ javascript skills

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.