2016-09-02 110 views
-19

我在这里有一个nodejs问题,我真的不知道它为什么会发生。为什么我在这里得到错误“不是函数”?

这里是我的代码:

\t isInTimeSlot() { 
 
\t \t return new Promise((resolve, reject) => { 
 
\t \t \t var date = new Date() 
 
\t \t  var hour = date.getHours() 
 
\t \t  hour = (hour < 10 ? "0" : "") + hour 
 
\t \t  var min = date.getMinutes() 
 
\t \t  min = (min < 10 ? "0" : "") + min 
 
\t \t  if (hour >= this.followMinHour && hour <= this.followMaxHour) { 
 
\t \t  \t return resolve(42) 
 
\t \t  } else if (hour >= this.unfollowMinHour && hour <= this.unfollowMaxHour) { 
 
\t \t  \t return resolve(1337) 
 
\t \t  } else { 
 
\t \t  \t return reject() 
 
\t \t  } 
 
\t \t }) 
 
\t } 
 

 
\t checkProjectTimeSlot() { 
 
\t \t return new Promise((resolve, reject) => { 
 
\t \t \t var timer = setInterval(function() { 
 
\t \t \t \t console.log('Checking if bot is in time slot') 
 
\t \t \t \t this.isInTimeSlot() 
 
\t \t \t \t .then((mode) => { 
 
\t \t \t \t \t clearInterval(timer) 
 
\t \t \t \t \t resolve(mode) 
 
\t \t \t \t }) 
 
\t \t \t }, 5000) \t \t 
 
\t \t }) 
 
\t }

因此,这里有2种我ES6类的简单方法,当我执行它,我有以下错误:

this.isInTimeSlot() 
        ^
TypeError: this.isInTimeSlot is not a function 

你能看到错误吗?

+7

请为您的问题找到一个更好的标题... – Yoshi

+0

当您进入您的承诺时,'this'不再指您期望的内容。阅读[这](http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/),你会解决它。 – byxor

+0

也许'this'指的是与你认为的不同的上下文。 ** WTF亚历克斯!** – siannone

回答

2

当您在承诺退货或定时器中时,您的this更改。

isInTimeSlot() { 
    return new Promise((resolve, reject) => { 
     var date = new Date() 
     var hour = date.getHours() 
     hour = (hour < 10 ? "0" : "") + hour 
     var min = date.getMinutes() 
     min = (min < 10 ? "0" : "") + min 
     if (hour >= this.followMinHour && hour <= this.followMaxHour) { 
      return resolve(42) 
     } else if (hour >= this.unfollowMinHour && hour <= this.unfollowMaxHour) { 
      return resolve(1337) 
     } else { 
      return reject() 
     } 
    }) 
} 

checkProjectTimeSlot() { 
    var that = this; 
    return new Promise((resolve, reject) => { 
     var timer = setInterval(function() { 
      console.log('Checking if bot is in time slot') 
      that.isInTimeSlot() 
      .then((mode) => { 
       clearInterval(timer) 
       resolve(mode) 
      }) 
     }, 5000)   
    }) 
} 
相关问题