How to create a new object in javascript: 1. Create a new object in the form of a literal; 2. Create a new object in the form of new Object().
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
How to create a new object in javascript?
There are two syntaxes for creating an object in JavaScript:
One is through literal form, the other is through new Object() The form
Creates a person object which has attributes such as name, age, sex, etc.
1. Literal syntax
var person = {name:"chen",age:12,sex:"male"};
2. New Object() form
var person = new Object(); person.name="test"; person.age=12; person.sex="male";
When declaring objects in JS, most people will write var a = {};Very few people write like this: var a = new Object();
Why?
{}This is called an object literal, and new Object() uses the constructor function.
The declaration method of object literals is more convenient than the constructor function.
So in JS it is recommended to give priority to object literal declarations
In JavaScript, using the new keyword means doing the following four things:
Create a new object, the type of this object is object;
Set the internal, accessibility and [[prototype]] properties of this new object to the constructor (referring to the constructor pointed to by prototype.construtor );
Execute the constructor, and when the this keyword is mentioned, use the properties of the newly created object;
Return the newly created object (unless returned in the constructor is 'no prototype').
Video tutorial recommendation: "javascript basic tutorial"
The above is the detailed content of How to create a new object in javascript. For more information, please follow other related articles on the PHP Chinese website!