//第一个参数为构造原型,第二个参数为传参数组
function myNew(Obj, ...args){
//创建一个空对象,这个空对象的原型和Obj一样
const obj = Object.create(Obj.prototype)
//创建一个对象,这个对象使用Obj的构造方法加上传进来的参数构造的
const res = Obj.apply(obj, ...args)
//如果构造方法返回对象,则返回此构造对象
if(res instanceof Object || res instanceof Function){
return res
}
//如果构造方法没有返回对象,则返回一开始的空对象
return obj
}
function Human(name, age){
this.name = name;
this.age = age
}
let human1 = myNew(Human, ["Tom", "10"]) //使用自己的new方法创建
console.log("使用自己的new方法创建");
console.log(human1);
let human2 = new Human("Bob", "20")//使用自带的new方法创建
console.log("使用自带的new方法创建");
console.log(human2);
JS:new的原理
最新推荐文章于 2024-06-14 15:02:13 发布