⚠ Prerequisites:
1 Introduction to the new operator MDN documentation: The 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 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 obj.__proto__ = Person.prototype Calls the constructor Person.apply(obj) If the constructor does not explicitly return an object, the newly created object is returned, i.e. 3 Simulate the implementation of the new operator As mentioned above, the 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 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
function Person() { ... return 1 } If the constructor explicitly returns an object, such as Then 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
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:
|
<<: Example of deploying MySQL on Docker
>>: Detailed explanation of memory management of MySQL InnoDB storage engine
This article summarizes some simple principles of...
How to install Linux CentOS 7.7 system in Vmware,...
Because Ubuntu 20.04 manages the network through ...
A list is defined as a form of text or chart that...
Table of contents Preface React Functional Compon...
Table of contents JSX environment construction In...
Detailed explanation of Linux LVM logical volume ...
Click here to return to the 123WORDPRESS.COM HTML ...
Method 1: <input id= "File1" type= &q...
Create a new project test1 on Code Cloud Enter th...
Table of contents App Update Process Rough flow c...
Everyone may be familiar with the select drop-dow...
Table of contents 1. What is dynamic typing? 2. D...
This article takes the health reporting system of...
Specify in CSS style file #class td /*Set the tab...