


How to create objects in js? Methods to create objects in js (with code)
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') }
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') } };
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')
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')
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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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.

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

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

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values are passed and object references are passed.

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.

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.

The Request object in PHP is an object used to handle HTTP requests sent by the client to the server. Through the Request object, we can obtain the client's request information, such as request method, request header information, request parameters, etc., so as to process and respond to the request. In PHP, you can use global variables such as $_REQUEST, $_GET, $_POST, etc. to obtain requested information, but these variables are not objects, but arrays. In order to process request information more flexibly and conveniently, you can
