Table of Contents
Call the system's constructor
Object Literal
Constructor Pattern
Home Web Front-end JS Tutorial JavaScript creates objects

JavaScript creates objects

Apr 10, 2018 pm 04:48 PM
javascript js create

The content of this article is about creating objects with JavaScript, which has certain reference value. Friends in need can refer to it

Call the system's constructor

Create the most The simple way is to create an instance of Object, as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// 1. 调用系统的构造函数

var person = new Object();

 

// 添加属性

person.name = "小李";

person.age = 22;

person.sex = "F";

 

// 添加方法

person.eat = function () {

    console.log("我喜欢吃油炸榴莲.")

};

 

person.play = function () {

    console.log("我喜欢玩电子游戏.")

};

 

person.introduce = function () {

    console.log("我叫" + this.name + ", 今年" + this.age + "岁.");

};   

 

person.introduce();        // 输出:我叫小李, 今年22岁.

Copy after login

The above code creates an object named object and adds three properties and three methods to it.

Object Literal

However, although the Object constructor and object literal can be used to create a single object, creating an object in this way will generate a lot of repeated code. So people started to use the factory pattern. As follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

function createPerson(name, age, sex) {

    var object = new Object();

    person.name = "小李";

    person.age = 22;

    person.sex = "F";

    person.introduce = function () {

        console.log("我叫" + this.name + ", 今年" + this.age + "岁.");

    };

     

    return person;

}

 

var person0 = createPerson("小苏", "21", "M");

var person1 = createPerson("铁子", "27", "M");

Copy after login

The function createPerson() can construct a Person object containing all information based on the accepted parameters. This function can be called an unlimited number of times, and each time it returns an object containing three properties and one method. Although the factory pattern solves the problem of a large amount of code duplication caused by creating multiple similar objects, it does not solve the problem of object identification, that is, how to know the type of an object. With the development of JavaScript, another new pattern has emerged, that is, the constructor pattern.

Constructor Pattern

Constructors in ECMAScript can create objects of specific types. Native constructors like Object objects and Array objects automatically appear in the execution environment at runtime. In addition, we can also customize the constructor to customize the type and method of the object. For example, the previous example could be rewritten using the automatic constructor as the following code:

1

2

3

4

5

6

7

8

9

10

11

12

function Person(name, age, sex) {

    this.name = name;

    this.age  = age;

    this.sex  = sex;

     

    this.introduce = function () {

        console.log("我叫" + this.name + ", 今年" + this.age + "岁.");

    };

}

 

var person0 = createPerson("小苏", "21", "M");

var person1 = createPerson("铁子", "27", "M");

Copy after login

In this example, the Person() function replaces the createPerson() function. We noticed that the code in the Person() function has the following similarities with the createPerson() function:

  • The object is not explicitly created;

  • The properties and methods are directly assigned to this object;

  • There is no return statement.

In addition, you should also notice that the capital letter P is used at the beginning of the function name. By convention, constructors should always begin with an uppercase letter, and non-constructors should always begin with a lowercase letter.
To create a new instance of Person, the new operator must be used. Calling the constructor in this way actually goes through four processes:

  1. Create a new object;

  2. change the function of the constructor The domain is assigned to the new object (so this points to the new object);

  3. Execute the code in the constructor;

  4. Return this new object.


Related recommendations:

detailed explanation of creating a local server with node.js

Several JS creations Sharing the way of objects

Detailed explanation of three.js creating scene instances


The above is the detailed content of JavaScript creates objects. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a folder on Realme Phone? How to create a folder on Realme Phone? Mar 23, 2024 pm 02:30 PM

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create pixel art in GIMP How to create pixel art in GIMP Feb 19, 2024 pm 03:24 PM

This article will interest you if you are interested in using GIMP for pixel art creation on Windows. GIMP is a well-known graphics editing software that is not only free and open source, but also helps users create beautiful images and designs easily. In addition to being suitable for beginners and professional designers alike, GIMP can also be used to create pixel art, a form of digital art that utilizes pixels as the only building blocks for drawing and creating. How to Create Pixel Art in GIMP Here are the main steps to create pixel pictures using GIMP on a Windows PC: Download and install GIMP, then launch the application. Create a new image. Resize width and height. Select the pencil tool. Set the brush type to pixels. set up

How to create a family with Gree+ How to create a family with Gree+ Mar 01, 2024 pm 12:40 PM

Many friends expressed that they want to know how to create a family in Gree+ software. Here is the operation method for you. Friends who want to know more, come and take a look with me. First, open the Gree+ software on your mobile phone and log in. Then, in the options bar at the bottom of the page, click the "My" option on the far right to enter the personal account page. 2. After coming to my page, there is a "Create Family" option under "Family". After finding it, click on it to enter. 3. Next jump to the page to create a family, enter the family name to be set in the input box according to the prompts, and click the "Save" button in the upper right corner after entering it. 4. Finally, a "save successfully" prompt will pop up at the bottom of the page, indicating that the family has been successfully created.

How to Create a Contact Poster for Your iPhone How to Create a Contact Poster for Your iPhone Mar 02, 2024 am 11:30 AM

In iOS17, Apple has added a contact poster feature to its commonly used Phone and Contacts apps. This feature allows users to set personalized posters for each contact, making the address book more visual and personal. Contact posters can help users identify and locate specific contacts more quickly, improving user experience. Through this feature, users can add specific pictures or logos to each contact according to their preferences and needs, making the address book interface more vivid. Apple in iOS17 provides iPhone users with a novel way to express themselves, and added a personalizable contact poster. The Contact Poster feature allows you to display unique, personalized content when calling other iPhone users. you

A first look at Django: Create your first Django project using the command line A first look at Django: Create your first Django project using the command line Feb 19, 2024 am 09:56 AM

Start the journey of Django project: start from the command line and create your first Django project. Django is a powerful and flexible web application framework. It is based on Python and provides many tools and functions needed to develop web applications. This article will lead you to create your first Django project starting from the command line. Before starting, make sure you have Python and Django installed. Step 1: Create the project directory First, open the command line window and create a new directory

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

See all articles