​javascript面试题,实现链式调用

发布时间 2024-01-03 10:51:15作者: 华仔89

// 实现一个链式调用

// hello.name("George").sleep(3).like("sports");

// log:I'm George

// 3s后log:sleep after 3s

// log:I like sports

 根据要求构建new一个对象 
const hello = {}

在对象中构建函数name,sleep,like

const hello = {
    name(name){},
    sleep(time){},
    like(sport){}

}

填充hello对象内部方法和参数,定义一个tasks数组保存任务,然后再从任务列表每次取出一个任务执行,如下:

const hello = {
  tasks: [],
  name(name) {
    const fn = () => {
      console.log(`I am ${name}`);
      this.run();
    };
    this.tasks.push(fn);
    return this;
  },
  sleep(time) {
    const fn = () => {
      setTimeout(() => {
        console.log(`sleep after ${time}`);
        this.run();
      }, time * 1000);
    };
    this.tasks.push(fn);
    return this;
  },
  like(sport) {
    const fn = () => {
      console.log(`I like ${sport}`);
      this.run();
    };
    this.tasks.push(fn);
    this.run();
    return this;
  },
// 取出任务执行  
  run() {
    const fn = this.tasks.shift();
    fn && fn();
  },
};