Uses of newThe function of new is to create an instance object through a constructor. The relationship between the instance, the prototype and the constructor is shown in the following figure: Let’s summarize first
Detailed descriptionWhen executing the new operation, the following steps are performed in sequence: 1. Create an empty object
let obj = {} 2. The internal property __proto__ of the empty object is assigned to the prototype property of the constructor
function Foo(num) { this.number = num } obj.__proto__ = Foo.prototype 3. Point the constructor's this to an empty object
Foo.call(obj, 1) 4. Execute the code inside the constructor
5. Return the new object
Emulating the new operatorThe following myNew function simulates the behavior of the new operator: function myNew(func, ...args) { let obj = {} obj.__proto__ = func.prototype let res = func.apply(obj, args) return res instanceof Object ? res : obj } function Foo(num) { this.number = num } let foo1 = myNew(Foo, 1) console.log(foo1 instanceof Foo) // true console.log(foo1.number) // 1 let foo2 = new Foo(2) console.log(foo2 instanceof Foo) // true console.log(foo2.number) // 2 The instanceof operator is used above to determine whether the return value of the constructor is an instance of Object, that is, whether it is a reference type value; this is because all reference type values are instances of Object, and Object is the base type of all reference type values. Well, this is the end of this article about the principle of the new operator in JavaScript. For more relevant content about the principle of JS new operator, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Create a virtual environment using venv in python3 in Ubuntu
>>: Steps to install superset under win10 system
Table of contents Impact of full table scan on th...
Swiper is a sliding special effects plug-in built...
1. Go to the location where you want to store the...
We know that there are two ways to receive incomi...
The default table name is base_data and the json ...
The main text starts below. 123WORDPRESS.COM Down...
Copy code The code is as follows: <html> &l...
error message: ERROR 1862 (HY000): Your password ...
Recently, I have been working on several virtual ...
MouseEvent When the mouse performs a certain oper...
Effect If you use it, please optimize the code an...
Table of contents Install Software Management Ano...
The previous article wrote about how to manually ...
1. Use Centos image to build local yum source Sin...
Table of contents Single condition single data fi...