The general operation of the new operator
function User() { this.name = 'xiaoming'; this.age = 20; } const user = new User(); console.log(user); // {name: "xiaoming", age: 20}Copy the code
We get an instance object whose name is ‘xiaoming’ and age is 20
What does the new operator do
- We create an empty object
const obj = {};
// or
const obj = new Object();
Copy the code
- Link this object to another object (point the object’s _proto_ to the constructor’s prototype)
obj._proto_ = User.prototype;
Copy the code
-
Use the created obj as the context for this
-
Determine the return value of the constructor
Return as a value type (return 1;) : Discard the value and return obj; Return a reference type (return {name: 'hahah'}) : Return this (obj); return this (obj); return this (obj); So it's going to return obj}Copy the code
Write the complete new by hand
function myNew (Constr, ... Const obj = {}; // link object obj._proto_ = constr.prototype; // bind this let res = constr. call(obj,... args); Return res instanceof Object? res : obj; }Copy the code
inspection
function User(name, age) { this.name = name; this.age = age; return function aa() { console.log('qq') } } function myNew (Constr, ... Const obj = {}; // link object obj._proto_ = constr.prototype; // bind this const res = constr.call (obj,... args); Return res instanceof Object? res : obj; } const user = myNew(User, 'momo', 20); console.log(user);Copy the code
function User(name, age) { this.name = name; this.age = age; } function myNew (Constr, ... Const obj = {}; // link object obj._proto_ = constr.prototype; // bind this const res = constr.call (obj,... args); Return res instanceof Object? res : obj; } const user = myNew(User, 'momo', 20); console.log(user);Copy the code