Get the App
SLTechnology News&Howtos  ›  Development  › 

The method of creating objects by JavaScript

Shulou Source: shulou.com Published: 2022-06-01 05:11:26 10月10日 Update

This article mainly explains "the method of creating objects in JavaScript". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the method of creating objects in JavaScript".

With JavaScript, you can define and create your own objects.

There are different ways to create objects:

Define and create a single object, using object text.

Define and create a single object through the keyword new.

Define an object constructor, and then create an object of the construction type.

In ECMAScript 5, you can also create objects through the function Object.create ().

Use the literals of the object:

This is the easiest way to create an object.

Using object text, you can define and create objects in a single statement.

The object literal refers to the name: value pair (such as age:62) in curly braces {}.

The following example creates a new JavaScript object with four properties:

Example

Var person = {firstName: "Bill", lastName: "Gates", age:62, eyeColor: "blue"}

Spaces and line breaks are not important. Object definitions can span multiple lines:

Example

Var person = {

FirstName: "Bill"

LastName: "Gates"

Age:62

EyeColor: "blue"

}

Use the JavaScript keyword new:

The following example also creates a new JavaScript object with four properties:

Example

Var person = new Object ()

Person.firstName = "Bill"

Person.lastName = "Gates"

Person.age = 50

Person.eyeColor = "blue"

The results of the above two examples are the same. No need to use new Object ().

For simplicity, readability, and execution speed, use the first creation method (object literal method).

Thank you for your reading, the above is the content of "the method of creating objects by JavaScript". After the study of this article, I believe you have a deeper understanding of the method of creating objects by JavaScript, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Object method text example instance facet learning key keyword content single attribute different important two function can be passed readability name literal Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Linux Shulou Information Redmi Huawei