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
Preface I have always wanted to know how a SQL st...
Preface The blogger uses the idea IDE. Because th...
This article uses an example to describe how to r...
Background: position: sticky is also called stick...
The solution to forgetting the initial password o...
Don't be surprised if you see some kind of und...
Basically all e-commerce projects have the functi...
How to use if in Linux to determine whether a dir...
This article example shares the specific code of ...
What to do if you forget Windows Server 2008R2 So...
Today I received a disk alarm exception. The 50G ...
Preface Since vue3.0 was officially launched, man...
Table of contents Preface JS Magic Number Storing...
mysql query control statements Field deduplicatio...
Defining an array in Bash There are two ways to c...