面试题

作者: 月肃生 | 来源:发表于2019-05-20 10:50 被阅读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('清仓大甩卖,最后一天!')

相关文章

  • 面试材料

    面试经验 面试题1 面试题2 面试题3 面试题4 面试题5 面试题6――数据结构 面试题7――网络 面试题8――汇...

  • 高阶面试题

    webpack面试题 面试题:webpack插件 Git面试题 面试题:git常用命令 面试题:解决冲突 面试题:...

  • this的指向的面试题

    面试题1 面试题2 面试题3 面试题4

  • 面试所涉及的问题

    面试题参考1 : 面试题 面试题参考2 : 内存管理 面试题参考3 :面试题 ...

  • Android超实用最全面试大纲(三)

    文章目录: ANR面试题 OOM面试题 Bitmap面试题 UI卡顿面试题 内存泄漏面试题 内存管理面试题 一、A...

  • Android最全面试大纲(三)

    文章目录: ANR面试题 OOM面试题 Bitmap面试题 UI卡顿面试题 内存泄漏面试题 内存管理面试题 一、A...

  • 2022年web前端面试题

    web前端面试题分为:html/css面试题、javascript面试题、vue面试题、性能优化面试题、网络方面面...

  • ios面试题

    初级面试题 中级面试题 高级面试题 swift篇

  • Android超实用最全面试大纲(四)

    文章目录: 冷启动和热启动面试题 其他优化面试题 架构模式面试题 插件化面试题 热更新面试题 进程保活面试题 Li...

  • Android最全面试大纲(四)

    文章目录: 冷启动和热启动面试题 其他优化面试题 架构模式面试题 插件化面试题 热更新面试题 进程保活面试题 Li...

网友评论

      本文标题:面试题

      本文链接:https://www.haomeiwen.com/subject/tsbhzqtx.html