Home > Web Front-end > JS Tutorial > Introduction to the Object type of JavaScript_javascript skills

Introduction to the Object type of JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:06:20
Original
1074 people have browsed it

There are two ways to create Object instances. The first is to use the new operator followed by the Object constructor, as shown below:

Copy code The code is as follows:

var person = new Object();
person.name = "zxj";
person.age = 25;

Another way is to use object literal notation. Object literals are a shorthand form of object definitions that are intended to simplify the process of creating objects with a large number of properties. The code looks like this:

Copy code The code is as follows:

//Object literal
var person = {
name: "zxj",
age: 25
}

When defining an object through an object literal, the Object constructor will not actually be called.

Generally speaking, dot notation is used when accessing object properties, but square bracket notation can also be used to access object properties in JavaScript. When using square bracket syntax, the attribute to be accessed should be placed in the form of a string within square brackets, as follows:

Copy code The code is as follows:

alert(person["name"]) //zxj
alert(person.name) //zxj

There is no difference between the functions of the two, but the main advantage of the square bracket syntax is that you can access attributes through variables:

Copy code The code is as follows:

var propertyName="name";
alert(person[propertyName]); //zxj

If the attribute name contains characters that will cause syntax errors, or the attribute name uses keywords or reserved words, you can also use square bracket notation, for example:

Copy code The code is as follows:

person['first name'] = "zxj";

In general, it is recommended to use dot notation unless square bracket notation is necessary.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template