手写new操作符

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
posted @ 2021-01-14 16:54  HelloCoderRookie  阅读(753)  评论(0编辑  收藏  举报