search
HomeWeb Front-endJS TutorialHow 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

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
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft