Home > Web Front-end > JS Tutorial > body text

How to create a new object in javascript

藏色散人
Release: 2021-11-08 17:30:30
Original
3602 people have browsed it

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().

How to create a new object in javascript

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"};
Copy after login

2. New Object() form

 var person = new Object();
        person.name="test";
        person.age=12;
        person.sex="male";
Copy after login

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!

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