JS new和instanceof的实现

时间:2020-03-21 14:43:35   收藏:0   阅读:69
function isObject(value) {
  const type = typeof value;
  return value !== null && (type === ‘object‘ || type === ‘function‘);
}

/**
 * constructor 表示 new 的构造器
 * args 表示传给构造器的参数
 */
function New(constructor, ...args) {
  // new 的对象不是函数就抛 TypeError
  if (typeof constructor !== ‘function‘) throw new TypeError(`${constructor} is not a constructor`);

  // 创建一个原型为构造器的 prototype 的空对象 target
  const target = Object.create(constructor.prototype);
  // 将构造器的 this 指向上一步创建的空对象,并执行,为了给 this 添加实例属性
  const result = constructor.apply(target, args);

  // 上一步的返回如果是对象就直接返回,否则返回 target
  return isObject(result) ? result : target;
}
function instanceOf(obj, constructor) {
  if (!isObject(constructor)) {
    throw new TypeError(`Right-hand side of ‘instanceof‘ is not an object`);
  } else if (typeof constructor !== ‘function‘) {
    throw new TypeError(`Right-hand side of ‘instanceof‘ is not callable`);
  }

  // 主要就这一句
  return constructor.prototype.isPrototypeOf(obj);
}

 

转自:https://juejin.im/post/5e2ff7dce51d4558021a1a4d

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!