2016-09-02 81 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)   
    }) 
} 
相關問題