🎯 summary
- Create an empty object
- An internal property of an empty object
__proto__
Assigned to the constructorprototype
attribute - Constructor
this
Pointing to an empty object - Execute the constructor internal code
- Returns the new object
Detailed instructions
The new operation goes through the following steps:
-
Create an empty object
- An empty Object is an instance of Object, i.e
{}
。
let obj = {} Copy the code
- An empty Object is an instance of Object, i.e
-
The empty object’s internal __proto__ attribute is assigned to the constructor’s Prototype attribute
- This is done to link the empty object to the correct stereotype
function Foo(num) { this.number = num } obj.__proto__ = Foo.prototype Copy the code
-
Point the constructor’s this to an empty object
- That is, this inside the constructor is assigned an empty object so that the constructor will be executed correctly later.
Foo.call(obj, 1) Copy the code
-
Execute the constructor internal code
- Add properties and methods to empty objects.
-
Returns the new object
- If the constructor internally returns a reference type value via a return statement, the new operation eventually returns the reference type value. Otherwise return the newly created object.
- Reference type values: All values except basic type values (numeric, string, Boolean, NULL, undefined, Symbol).
Emulate the new operator
The following myNew function emulates 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
Copy the code
The instanceof operator is used to determine whether the return value of the constructor is an instanceof Object, that is, a reference type value. This is because all reference type values are instances of Object, the base type of all reference type values.