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

Simple principles for web page layout design

This article summarizes some simple principles of...

Detailed tutorial on VMware installation of Linux CentOS 7.7 system

How to install Linux CentOS 7.7 system in Vmware,...

Ubuntu 20.04 sets a static IP address (including different versions)

Because Ubuntu 20.04 manages the network through ...

A comprehensive understanding of Vue.js functional components

Table of contents Preface React Functional Compon...

Markup Languages ​​- What to learn after learning HTML?

Click here to return to the 123WORDPRESS.COM HTML ...

How to upload projects to Code Cloud in Linux system

Create a new project test1 on Code Cloud Enter th...

A brief discussion on React native APP updates

Table of contents App Update Process Rough flow c...

Web page custom selection box Select

Everyone may be familiar with the select drop-dow...

This article takes you into the world of js data types and data structures

Table of contents 1. What is dynamic typing? 2. D...

Docker+selenium method to realize automatic health reporting

This article takes the health reporting system of...