首页 > 其他 > 详细

手写new操作符

时间:2021-01-14 17:09:17      阅读:26      评论:0      收藏:0      [点我收藏+]

JS中的new 的关键底层机制:new到底干了啥?

  1. 创建一个空的对象 const obj = {};
  2. 设置obj._proto_ = Fn.prototype,绑定this到obj上, 执行Fn(构造函数)
  3. 如果2中的Fn返回的不是引用类型,则返回obj

手写new :可以看到下面的new的实现基本上是按照以上步骤的

function _new(Fn, ...args) {
        const obj = {};
        obj.__proto__ = Fn.prototype;
        let res = Fn.call(obj, ...args);
        if ((res !== null) && (typeof res === ‘object‘ || typeof res === ‘function‘)) {
            return res;
        }
        return obj;
    }

测试一下

function Dog(name, age) {
        this.name = name;
        this.age = age;
    }
    Dog.prototype.sayInfo = function() {
        console.log(`Name = ${this.name}, Age = ${this.age}`);
    }
    let dog = _new(Dog, ‘Hello‘, 12);
    dog.sayInfo();s

参考:

  • ? MDN

手写new操作符

原文:https://www.cnblogs.com/rookie123/p/14278116.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!