new的时候发生了什么?

版权声明:任先阳 任 先 阳 任先 先阳,ifgm.cn、www.ifgm.cn、nvcc.cc、www.nvcc.cc、sbfox.com、www.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>

猜你喜欢

转载自blog.csdn.net/qq_39571197/article/details/86467045
今日推荐