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

Detailed explanation of Xshell common problems and related configurations

This article introduces common problems of Xshell...

Data URI and MHTML complete solution for all browsers

Data URI Data URI is a scheme defined by RFC 2397...

Vue's guide to pitfalls using throttling functions

Preface In a common business scenario, we need to...

What to do if you forget the initial password of MySQL on MAC

The method to solve the problem of forgetting the...

JavaScript regular verification password strength implementation method

exhibit design Password strength analysis The pas...

Detailed description of mysql replace into usage

The replace statement is generally similar to ins...

MySQL 8.0.18 uses clone plugin to rebuild MGR implementation

Assume that a node in the three-node MGR is abnor...

JS 4 super practical tips to improve development efficiency

Table of contents 1. Short circuit judgment 2. Op...

HTML meta viewport attribute description

What is a Viewport Mobile browsers place web page...

MySQL changes the default engine and character set details

Table of contents 1. Database Engine 1.1 View dat...

Analysis of Sysbench's benchmarking process for MySQL

Preface 1. Benchmarking is a type of performance ...

CocosCreator learning modular script

Cocos Creator modular script Cocos Creator allows...

Detailed explanation of HTML basics (Part 1)

1. Understand the WEB Web pages are mainly compos...