0

clipboard.png

sinson 126
2019-03-15 提问
4 个回答
0

已采纳
class AI{

 constructor(){

    this.queue = []; //1代表talk 2代表cancel 3代表sleep
}

talk(){
let self = this;

new Promise(function(resolve,reject){

    self.queue.push(1);
    resolve();

}).then(function(res){
    
     if(self.queue.length >= 2){
        if(self.queue[0] == 1 && queue[1] == 2){
            self.queue.splice(0,2);
        }else{
            self.queue.shift();
            console.log("talk");
        }
    }else if(self.queue[0] == 1){
        self.queue.shift();
        console.log("talk");
    }
})
return this;
}

cancel(){
var self = this;
new Promise(function(resolve,reject){
    self.queue.push(2);
    resolve();
}).then(function(res){
    if(self.queue[0] ==2){
        self.queue.shift();
        console.log("no task");
    }else{
        console.log("cancel");
    }
})
return this;
}

sleep(n){
    var self = this;
    new Promise(function(resolve,reject){
        self.queue.push(3);
        resolve();
    }).then(function(res){
        console.log(`等待${n}秒`);
        self.queue.shift();
    })
  return this;
}
}

0
  function AI() {
      this.talk = function (bool) {
         if (bool) {
             this.cancel = function () {
                console.log("cancel");
             };
        } else {
            console.log('talk')
         }
         return this;
     };
     this.cancel = function () {
        console.log("no task");
     };
     return this;
 }
0

如果你指的输出是返回值的话, 基本类型的输出必定做不到
如果你指的是控制台输出的话则可以用setTimeout来延迟决定输出内容, 如下

function AIFactory(state, clearFn) {
  return {
    state: state||0,
    cancel: function() {
      if (clearFn != null) clearFn()
      if (this.state === 0) {
        setTimeout(function() {
          console.log("no task")
        })
      } else {
        setTimeout(function() {
          console.log("cancel")
        })
      }
    },
    talk: function() {
      const timeoutId = setTimeout(function() {
        console.log("talk")
      })
      const clearFn = function() {
        clearTimeout(timeoutId)
      }
      return AIFactory(1, clearFn)
    }
  }
}

var AI = AIFactory()
0

链式调用的关键在于尾部返回this

let AI = function(...arr){
    this.talkArr = arr;
    this.times = null
}
AI.prototype.talk = function(){
    this.times = setTimeout(()=>{
        let talk = this.talkArr.pop()
        this.times = null
        console.log(talk)
    })
    return this
}
AI.prototype.cancel = function(){
    if(this.times){
        clearTimeout(this.times)
        this.times = null
        console.log('cancel')
    }else{
        console.log('no task')
    }
    return this
}

var ai = new AI('talk1','talk2');
//--------------
ai.talk(); // talk2

//-------------
ai.cancel(); // 'no task'

//-------------
ai.talk();
ai.cancel();

//等价于
ai.talk().cancel(); // cancel

撰写答案

推广链接