function myNew(Obj, ...args) {
let obj = Object.create(Obj.prototype);//使用指定的原型对象及其属性去创建一个新的对象
let ret = Obj.apply(obj,args); // 绑定 this 到obj, 设置 obj 的属性
if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
return ret;
}
return obj; //确保构造器总是返回一个对象
}
function Foo(name, age) {
this.name = name;
this.age = age
}
let tom = new Foo('tom', 18) // {name: "tom", age: 18}
let kim = myNew(Foo, 'kim', 20) //{name: "kim", age: 20}