面试题

2019-05-20  本文已影响0人  月肃生
  1. 实现一个promise
class A {
  constructor(fn) {
    let that = this
    that.value = null
    that.onFullFn = {thenFn: function(){}, thenResolve: function(){}} // then的回调
    that.onFailFn = {}
    this.then = this.then.bind(this)
    function resolve(value) {
      setTimeout(() => {
        that.value = value
        that.onFullFn.thenResolve(that.onFullFn.thenFn(that.value)) 
      },0)
    }
    function reject(error) {
      setTimeout(() => {
        that.error = error
      }, 0)
    }
    fn(resolve, reject)
  }
  
  then(fn) {
    return new A((resolve, reject) => {
      this.onFullFn={thenFn: fn, thenResolve: resolve}
    })
  }
}
  1. 实现一个EventEmitter
class EventEmitter {
 constructor() {
   this.on = this.on.bind(this);
   this.once = this.once.bind(this);
   this.off = this.off.bind(this);
   this.trigger = this.trigger.bind(this);
   this.onFns = {}; // 注册方法
 }
 on(name, fn) {
   this.onFns[name] = {
     fn: fn,
     type: "always"
   };
 }
 once(name, fn) {
   let that = this;
   this.onFns[name] = {
     fn: function() {
       fn();
       delete that.onFns[name];
     },
     type: "once"
   };
 }
 off(name) {
   delete this.onFns[name];
 }
 trigger(name) {
   if (this.onFns[name]) {
     this.onFns[name].fn();
   }
 }
}
  1. 观察者模式
class Subject {
  constructor() {
    this.observers = []
    this.subscribe = this.subscribe.bind(this)
    this.pushMessage = this.pushMessage.bind(this)
  }
  subscribe(observer) {
    this.observers.push(observer)
  }
  pushMessage(message) {
    this.observers.forEach(item => {
      item.update(message)
    })
  }
}
class Observer {
  constructor(name) {
    this.name = name
    this.update = this.update.bind(this)
  }
  update(message) {
    console.log(this.name, message)
  }
}
const sub = new Subject()

const observer1 = new Observer('张三')
const observer2 = new Observer('李四')
const observer3 = new Observer('王五')
const observer4 = new Observer('麻溜')
sub.subscribe(observer1)
sub.subscribe(observer2)
sub.subscribe(observer3)
sub.subscribe(observer4)

sub.pushMessage('全场3.5折,买到就是赚到!')
sub.pushMessage('清仓大甩卖,最后一天!')
上一篇 下一篇

猜你喜欢

热点阅读