new的时候发生了什么?

版权声明:任先阳,ifgm.cn、nvcc.cc、sbfox.com https://blog.csdn.net/qq_39571197/article/details/86467045
<script>
  const newFn = function (C, ...args) {
    /**
     * 创建对象,将其__proto__关联到构造器的prototype
     * 设置原型
     * 判断返回值
     * 输出
     * */
    // const obj = Object.create(C.prototype);
    /* 等价于 */
    const obj = {
      __proto__: C.prototype,
    };
    const instance = C.apply(obj, args);
    if (instance && (typeof(instance) === 'object' || typeof(instance) === 'Function')) {
      return instance;
    }
    return obj;
  };

  function Person(name) {
    this.name = name;
  }

  Person.prototype.logName = function () {
    console.log(this.name);
  };

  const o = newFn(Person, '任先阳');
  o.logName();
</script>

补充一下,ES6新增了Object.getPrototypeOf、Object.setPrototype两个方法,用来操作 __proro__  属性。

<script>
  const newFn = function (C, ...args) {
    const result = {};
    Object.setPrototypeOf(result,C.prototype); // here
    const instance = C.apply(result, args);
    if (instance && (typeof(instance) === 'object' || typeof(instance) === 'Function')) {
      return instance;
    }
    return result;
  };

  function Person(name) {
    this.name = name;
  }

  Person.prototype.logName = function () {
    console.log(this.name);
  };

  const o = newFn(Person, '任先阳');
  o.logName();
</script>

 

没有更多推荐了,返回首页