Object.create,extend,instanceof,Event的实现

304 阅读1分钟

步骤口述参数,实现笔试参考

实现Object.create

步骤

  • 创建空函数,将参数作为函数的prototype
  • 返回空函数new出来的实例(将__proto__prototype关联)

实现

function create(proto) {
  function F(){}
  F.prototype = proto;
  return new F();
}

实现继承

步骤

  • 属性通过构造函数
  • 方法通过原型

实现

// 组合:父类实例化2ci
function P(){}
function C() {
  P.call(this)
}
C.prototype = new P();
C.prototype.constructor = C;

// 寄生组合
function object(proto) {
  function F(){};
  F.prototype = proto;
  return new F(); // 实例化的是空函数,性能影响不大
}
function inheritProto(sub, super) {
  // object同Object.create
  const prototype = object(super.prototype);
  prototype.constructor = sub; // 设置构造函数
  sub.prototype = prototype;
}

function P(){}
function C() {
  P.call(this)
}
inheritProto(C, P)

实现instanceof

步骤

  • 沿着对象的__proto__原型链,判断是否构造函数的prototype相等

实现

function mockInstanceof(obj, Constr) {
  const target = Constr.prototype;
  let proto = obj.__proto__;
  while(true) {
    if (proto === null) return false;
    if (proto === target) return true;
    proto = proto.__proto__;
  }
}

实现Event

步骤

  • 利用map存储,事件名称/回调函数(支持多个监听需要用数组维护)
  • on时候,往map设置
  • emit时候,查找时间名称,调用函数
  • remove时候,查找名称,从map中删除

实现

function mockEvent() {
  this.events = new Map();
  this.max = 10;
}

mockEvent.prototype.on = function(type, fn) {
  if (!this.events.get(type)) {
    this.events.set(type, fn);
  }
}

mockEvent.prototype.emit = function(type, ...args) {
  const handler = this.events.get(type);
  if (handler) {
    if (args.length > 0) {
      handler.apply(this, args);
    } else {
      handler.call(this);
    }
  }
}

mockEvent.prototype.remove = function(type, fn) {
  if (this.events.get(type)) {
    this.events.delete(type, fn);
  }
}