⚠ 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
Permission denied: The reason for this is: there ...
Examples: Through the PHP background code, you ca...
Enable WSL Make sure the system is Windows 10 200...
This article shares the installation tutorial of ...
1. Rendering 2. Source code HTML < body > &...
When building a database and writing a program, i...
In many cases, arrays are often used when writing...
Table of contents background Purpose Before split...
The file server is one of the most commonly used ...
Preface Transactional data dictionary and atomic ...
1. Linux under VMware Workstation: 1. Update sour...
Table of contents 1. Import files using script ta...
Preface: This article mainly introduces the query...
MySQL8.0.22 installation and configuration (super...
1. Add users and groups 1. Add mysql user group #...