手写 new
1. new User() 通过构造函数创建的对象的 __proto__ 指向构造函数的原型.
2. User() 构造函数中的 this 指向 User() 构造函数的实例对象.
function myNew(target){ let result = {}; let arg = Array.prototype.slice.call(arguments, 1); // 将实例对象的 __proto__ 指向 target.prototype Object.setPrototypeOf(result, target.prototype); // this 指向实例对象 target.apply(result, arg); return result; } // 测试 function User(name, age) { this.name = name; this.age = age; } let user = myNew(User, "Jason", 23); console.log(user.__proto__ === User.prototype); // true

浙公网安备 33010602011771号