参考资料
new 关键字
new
关键字会进行如下的操作:
- 创建一个空的简单JavaScript对象(即
{}
); - 为步骤1新创建的对象添加属性
__proto__
,将该属性链接至构造函数的原型对象 ; - 将步骤1新创建的对象作为
this
的上下文 ; - 如果该函数没有返回对象(null可不是对象),则返回
this
。
代码如下:
function test1(age){
this.age = age;
}
test1.prototype.say = function(){
return "hello"
}
function test2(age){
this.age = age;
return null;
}
function test3(age){
this.age = age;
return {
age:30
};
}
const newfun = function(constructor,...args){
let obj = Object.create(constructor.prototype);
let res = constructor.apply(obj,[...args]);
if(res === null) return obj;// 需要特判一下
return typeof res === "object" ? res : obj;
}
const res1 = newfun(test1,1);
const res2 = newfun(test2,1);
const res3 = newfun(test3,1);
console.log(res1,res1.say());
console.log(res2);
console.log(res3);