⚠ 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 uses an example to describe how MySQ...
After installing the latest Windows 10 update, I ...
Problem Description By configuring nginx, you can...
What is content overflow? In fact, when there is ...
1. Create a new UI project First of all, our UI i...
Table of contents Main issues solved 1. The data ...
Table of contents 1. Vue life cycle 2. Hook funct...
Table of contents first step: The second step is ...
Table of contents Typical Cases Appendix: Common ...
Table of contents Preface advantage: shortcoming:...
For containers, the simplest health check is the ...
Table of contents 1. The role of index 2. Creatin...
One sentence to introduce HOC What is a higher-or...
In cells, dark border colors can be defined indiv...
Cocos Creator modular script Cocos Creator allows...