Handwriting implementation of new in JS

Handwriting implementation of new in JS

⚠ Prerequisites:

  • Understanding prototypes and prototype chains
  • Understanding this binding

1 Introduction to the new operator

MDN documentation: The new operator creates an instance of a user-defined object type or an instance of a built-in object with a constructor.

class Person {
    constructor(name) {
        this.name = name;
    }
}
// Create an instance of a custom object type const person = new Person('Xiao Ming')
// Create an instance of a built-in object with a constructor const date = new Date()


The role of new: create an instance of an object

2 What did new do?

It was mentioned above that the function of new is to create an instance of an object, so how does it create an instance and what does it do internally?

Take new Person() as an example. When it is executed, the following things happen:

Create an empty simple JS object

const obj = {}


Add the attribute __proto__, to this object and link the attribute to the prototype object of the constructor

obj.__proto__ = Person.prototype


Calls the constructor Person and binds this to the newly created object obj

Person.apply(obj)


If the constructor does not explicitly return an object, the newly created object is returned, i.e. obj

3 Simulate the implementation of the new operator

As mentioned above, the new operator does four things. Let's use functions to simulate the implementation of new according to these four steps (handwritten code for the interview)

const _new = function(constructor, ...args) {
    const obj = {}
    obj.__proto__ = constructor.prototype
    const res = constructor.apply(obj, args)
    // This step will be explained in detail in "Supplement" return res instanceof Object ? res : obj
}

The code is very simple, just follow the above 4 steps and write it step by step

4 Supplement

ES5 provides the Object.create method, which can create an object and let the __proto__ property of the new object point to the existing object.

So we can use this method to combine steps 1 and 2

const obj = Object.create(constructor.prototype)
// Equivalent to const obj = {}
obj.__proto__ = constructor.prototype

For step 4, explain

  • If the constructor does not explicitly return (usually), then person is the newly created object obj
  • If the constructor does not return an object, such as 1, "abc", then person is still the newly created object obj
function Person() {
    ...
   return 1
}

If the constructor explicitly returns an object, such as {} , function() {}

Then person is not the newly created object obj , but the object explicitly return .

function Person() {
  // Functions are also objects return function() {}
}

So the last line of code in our _new function is:

return res instanceof Object ? res : obj


Note: The parameter passed to the simulated function _new can only be a constructor, not a class

class Animal { ...}_new(Animal) // Will report an error: Class constructor Animal cannot be invoked without 'new' // Classes can only be created using new

This is the end of this article about handwritten implementation of new in JS. For more relevant new content in JS, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • The relationship between JS constructor and instantiation and prototype introduction
  • Detailed explanation of JavaScript prototype and examples
  • An article to help you understand Js inheritance and prototype chain
  • Summary and practice of javascript prototype chain diagram
  • Detailed description of the function of new in JS
  • How much do you know about JavaScript's constructor, prototype, prototype chain and new?

<<:  Example of deploying MySQL on Docker

>>:  Detailed explanation of memory management of MySQL InnoDB storage engine

Recommend

Detailed explanation of the solution to permission denied in Linux

Permission denied: The reason for this is: there ...

How to install WSL2 Ubuntu20.04 on Windows 10 and set up the docker environment

Enable WSL Make sure the system is Windows 10 200...

MySQL 8.0.12 winx64 detailed installation tutorial

This article shares the installation tutorial of ...

CSS and JS to achieve romantic meteor shower animation

1. Rendering 2. Source code HTML < body > &...

How to choose the right MySQL datetime type to store your time

When building a database and writing a program, i...

Example code and method of storing arrays in mysql

In many cases, arrays are often used when writing...

Vue project code splitting solution

Table of contents background Purpose Before split...

Detailed steps to build a file server in Windows Server 2012

The file server is one of the most commonly used ...

Detailed explanation of Linux copy and paste in VMware virtual machine

1. Linux under VMware Workstation: 1. Update sour...

Javascript uses the integrity attribute for security verification

Table of contents 1. Import files using script ta...

MySQL query syntax summary

Preface: This article mainly introduces the query...

MySQL 8.0.22 installation and configuration graphic tutorial

MySQL8.0.22 installation and configuration (super...