new 关键字

43 阅读1分钟

new关键字,到底干了什么?

  • 创建了一个对象
  • 这个对象的原型(__proto__),指向了构造函数的prototype
  • 该对象实现了构造函数的方法
  • 根据一些特定的情况返回对象
    • 如果这个构造函数没有返回值,或者返回了一个非对象类型,则new最后返回创建的这个对象
    • 如果这个构造函数明确返回了一个对象,则返回这个对象

实现new关键字

function newFunc(Person, ...rest) {
    if (typeof Person !== 'function') {
        throw new Error('new operator function the first param must be a function');
    }
    // 创建了一个对象
    // 该对象的__proto__ ,指向了Person的prototype
    const obj = Object.create(Person.prototype);
    // 这个对象实现了Person的方法
    const result = Person.apply(obj, rest);
    // 根据特定的情况返回对象
    return result && typeof result === 'object' ? result : obj;
}

使用

image.png

实现 Object.create

function inherit(p) {
    if (p === null) {
        throw TypeError();
    }
    function f(){};
    f.prototype = p;
    return new f();
}