Table of Contents
1. Create through the Object constructor (only a single object can be created)
2. Create objects through literals (only a single object can be created)
3. Factory pattern
4. Constructor pattern
Home Web Front-end JS Tutorial How to create objects in js? Methods to create objects in js (with code)

How to create objects in js? Methods to create objects in js (with code)

Aug 11, 2018 am 10:17 AM
javascript object

The content of this article is about how to create objects in js? The method of creating objects in js (with code) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There are 4 magic weapons for creating objects

1. Create through the Object constructor (only a single object can be created)

let obj = new Object();
obj.name = '命名最头痛'
obj.age = 18
obj.job = function() {
    console.log('programer')
}
Copy after login

This method is to create a single object without encapsulation The flexibility is negligible, and every time you add an attribute, you have to write obj once, and the readability of the code is not very good. Just understand it.

2. Create objects through literals (only a single object can be created)

let obj = {
    name: '命名最头痛',
    age: '18,
    job: function() {
        console.log('programer')
    }
};
Copy after login

This method is also a single object method. Compared with the previous method, although it enhances readability, it The problem of encapsulation is still not solved. We hope to encapsulate common parts to enhance reusability and create them by passing parameters. At this time, the function method came into being.

3. Factory pattern

Factory factory wraps things up like a factory

function createObj (name, age, job) {
  let obj = new Object();
  obj.name = name,
  obj.age = age,
  obj.job = function() {
    console.log(job)
  }
  return obj;
}
let obj = createObj('命名最头痛', 18, 'programer')
Copy after login

The design idea of ​​the factory pattern is to create an object in a function and finally return it This object can create a new object every time it is called.
Although this method solves the encapsulation problem, it still cannot meet our needs because it does not know the type of object. At this time, a new pattern appears again.

4. Constructor pattern

We know that the constructor in ECMA can be used to create specific types of objects. In addition to the Object constructor, we can also create Custom constructor that defines the properties of the object type.

function Obj (name, age, job) {
  this.name = name
  this.age = age
  this.job = function() {
    console.log(job)
  }
}

let obj1 = new Obj('命名最头痛', 18 'programer')
let obj2 = new Obj('命名最头痛', 18 'programer')
Copy after login

I have been wondering before What is the difference between a structure constructor and a function , and later I discovered that any function can be used as a constructor as long as it is called through the new operator , and any function, if it is not called through the new operator, is no different from an ordinary function, it has the same properties, but is used in different places and has different names.

Here, we discovered a mysterious new word, new, yes, the word new is used to create objects, so what exactly is done behind new?

①Create a new object
②Assign the scope of the constructor to the new object (so this points to the new object)
③Execute the code in the constructor (add for this new object Properties)
④Return a new object

Okay, we know that new can create an object, so what do we call the created thing? We call it instance.
After creating an instance, the instance will be attached with a constructor (constructor) attribute, through which you can find its constructor. If you don’t understand this sentence, let me make an analogy to understand it. , creating an object is like a tadpole mother, and an instance is like a tadpole. After the tadpole mother gives birth to the tadpoles, she will leave birthmarks (constructor) on them, and the tadpoles can use this birthmark to find their mother.

So what are the advantages of this method over the previous one?

Creating a custom constructor means that its instance can be identified as a specific type, which solves the problem of the factory pattern not being able to recognize the object type.

Perfect, the object recognition problem is solved, which means that when we see an object, we have a way to find its "motherboard" (through the constructor).

The constructor seems perfect, but it still has shortcomings. We all know that every time a constructor is created, an object is instantiated. Objects created by the same constructor have unequal functions with the same name. To put it bluntly, creating functions in this way, Will result in different scope chains and identifier resolution. If you still don’t understand, there is nothing that cannot be solved with a picture

How to create objects in js? Methods to create objects in js (with code)

This picture means: two objects created through the Person constructor p1 and p2, their functions with the same name (common methods) are not equal. (Attributes are not necessarily equal)

Article recommendation:

Create a linked list with js objects

Example of how to create an object with JS

The above is the detailed content of How to create objects in js? Methods to create objects in js (with code). 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)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

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

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

Analyze the differences between heap and stack in Java and their application scenarios Analyze the differences between heap and stack in Java and their application scenarios Feb 24, 2024 pm 11:12 PM

The difference between Java heap and stack and application scenario analysis require specific code examples. In Java programs, heap and stack are two commonly used data structures, and they assume different roles and functions in memory. Understanding the difference between heap and stack is crucial to writing efficient Java programs. First, let's take a look at the Java heap. The heap is an area used to store objects. All objects created in the program are stored in the heap. The heap is where memory is dynamically allocated and released while the program is running. It is not subject to any restrictions and can be automatically allocated and released as needed.

See all articles