- 首先创建一个新的空对象
- 根据原型链,设置空对象的__proto__为构造函数的prototype
- 构造函数的this指向这个对象,并执行构造函数的代码(为这个新对象添加属性)
- 判断函数的返回值类型,如果是引用类型,就返回这个引用类型的对象
function myNew(obj,...args) {
const newObj = Object.create(obj.prototype)
const res = obj.apply(newObj,args);
return typeof res === "object" ? res : newObj;
}
function Person(name, age) {
this.name = name
this.age = age
}
const obj = myNew(Person,'zs',18)
console.log(obj);