How to implement JavaScript's new operator yourself

How to implement JavaScript's new operator yourself

Constructor

Before introducing new, you must know what a constructor is.

There is no difference in writing between a constructor and an ordinary function. When a function is called through new Fun(), it is called a constructor, and the first letter of the constructor is usually capitalized.

function User(name) {
    this.name = name;
}

let u = new User('leo');

Here, User is the constructor. Of course, you can also call User() directly, but this will not create an instance. In non-strict mode, the name attribute will be hung on the window.

new Operator

So what exactly does the new operator do to create an instance?

The new operator creates an instance of a user-defined object type or an instance of a built-in object that has a constructor. The new keyword performs the following operations:

1. Create an empty simple JavaScript object (i.e. **{}**);

2. Link the object (i.e. set the object's constructor) to another object;

3. Use the newly created object in step 1 as the context of **this**;

4. If the function does not return an object, it returns **this**.

The above is quoted from the new operator - MDN

Maybe you don't understand steps 2 and 4 very well, so I will summarize them again here:

1. Create an empty object u = {}

2. Bind prototype, u.__proto__ = User.prototype

3. Call the User() function and pass the empty object u as this, that is, User.call(u)

4. If the User() function returns an object type after execution, then return this variable, otherwise return this. Note: If the constructor returns a basic type value, it will not be affected and still return this

Implement a new one yourself

Knowing the principle of the new operator, let's implement a FakeNew function ourselves.

function FakeNew() {
    let obj = {};
  
    // Convert the array-like arguments to an array and shift out the first parameter, which is the constructor let constructor = [].shift.apply(arguments);  

    // Bind prototype obj.__proto__ = constructor.prototype;    
  
    // Call the constructor and pass obj as this let res = Constructor.apply(obj, arguments);    

    // return return typeof res === 'object' ? res : obj;   
}

function User(name) {
    this.name = name;
}

User.prototype.getName = function() {
    return this.name;
}

let u = FakeNew(User, 'leo');
console.log(u);
console.log(u.getName());

The comments of the corresponding key steps have been attached to the code, so we have implemented a new operation. I believe that when you see new in the future, you will have a clearer feeling.

The above is the details of how to implement JavaScript's new operator yourself. For more information about JavaScript's new operator, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Let's talk in depth about the principle and implementation of new in JS
  • Detailed description of the function of new in JS
  • Detailed explanation of the principle and example of the new operator in JavaScript
  • Research on two ways to implement new in JavaScript
  • Detailed explanation of the role of the new operator in Js
  • Summary of common methods of c# Newtonsoft.Json
  • C# Newtonsoft.Json parses multiple nested json for deserialization example
  • c# add Newtonsoft.Json package operation
  • The new command in JavaScript
  • Handwriting implementation of new in JS

<<:  Example of how to implement keepalived+nginx high availability

>>:  MySQL 5.7.21 installation and password configuration tutorial

Recommend

Implementation of Docker deployment of web projects

The previous article has installed the docker ser...

Implementation of Webpack3+React16 code splitting

Project Background Recently, there is a project w...

Use docker to build kong cluster operation

It is very simple to build a kong cluster under t...

HTML end tag issue and w3c standard

According to the principles of W3C, each start tag...

Some data processing methods that may be commonly used in JS

Table of contents DOM processing Arrays method Su...

MySQL 8.0.22 decompression version installation tutorial (for beginners only)

Table of contents 1. Resource download 2. Unzip t...

How to configure VMware multi-node environment

This tutorial uses CentOS 7 64-bit. Allocate 2GB ...

Detailed explanation of computed properties in Vue

Table of contents Interpolation Expressions metho...

Let's talk about the size and length limits of various objects in MySQL

Table of contents Identifier length limit Length ...

Explaining immutable values ​​in React

Table of contents What are immutable values? Why ...

SELinux Getting Started

Back in the Kernel 2.6 era, a new security system...

New usage of watch and watchEffect in Vue 3

Table of contents 1. New usage of watch 1.1. Watc...

mysql5.7 create user authorization delete user revoke authorization

1. Create a user: Order: CREATE USER 'usernam...

Recommend 60 paging cases and good practices

<br />Structure and hierarchy reduce complex...

HTML table markup tutorial (2): table border attributes BORDER

By default, the border of the table is 0, and we ...