JavaScript之手动模拟new关键字

参考资料

new 运算符 - JavaScript | MDN (mozilla.org)

Object.create() - JavaScript | MDN (mozilla.org)

new 关键字

new 关键字会进行如下的操作:

  1. 创建一个空的简单JavaScript对象(即{});
  2. 为步骤1新创建的对象添加属性__proto__,将该属性链接至构造函数的原型对象 ;
  3. 将步骤1新创建的对象作为this的上下文 ;
  4. 如果该函数没有返回对象(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);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值