function modelNew(Parent, ...test) {
if(typeof Parent !== 'function'){
throw 'newOperator function the first param must be a function';
}
// 1.创建一个空对象
let target = {};
// 2.把Parent的this指向target
target.__proto__ = Parent.prototype;
// 3.执行parent的代码为target添加属性,如果构造函数有返回结果,则接收
let result = Parent.apply(target, test)
if (typeof result === "object" || typeof result === "function" && result !== null) {
return result
}
// 4.返回这个对象
return target
}
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayName = function () {
console.log(this.name);
}
let child = modelNew(Person, 'andy', 21);
console.log(child); // Person {name: "andy", age: 21}
child.sayName() // 'andy'
手写new实现原理
最新推荐文章于 2022-08-09 15:14:23 发布