2017-02-19 65 views
0

我有以下代碼本的NodeJS參考

this.userInfo = 'bla'; 

    request({ 
     url: 'https://api.api.ai/v1/entities?v=20150910', 
     headers : { 
      Authorization: "Bearer " + process.env.APIAI_ACCESS_TOKEN 
     }, 
     method: 'GET' 
    }, function (error, response, body) { 
     if (error) { 
      console.log('Error sending message: ', error); 
     } else if (response.body.error) { 
      console.log('Error: ', response.body.error); 
     } 
     console.log(this.userInfo); 
    }.bind(this)); 

當我嘗試打印this.userInfo可變我得到undefined,但我對this做了bind()。有人能解釋我發生了什麼事嗎?

+0

似乎應該可以工作良好,你必須重新分配'userInfo' –

+0

亞歷山德羅,這個範圍是失去了在您使用this.userInfo – anomepani

回答

0

我強烈建議檢查一下MDN article on the this keyword in JavaScript,對我來說,看起來您誤解了JavaScript中this關鍵字的用途。

在Node.js中也有所不同,在全球範圍的瀏覽器中,this始終爲window

在Node.js中,所有模塊都在其自己的閉包中執行,而默認情況下,瀏覽器運行全局範圍。

TL; DR據我所知你不能在JS中編寫這樣的代碼。 Check out this StackOverflow answer for more detail

而不是使用this您可能需要在該模塊中設置一個變量,並將userInfo存儲到該變量中。

3

在您的代碼範圍this被其他函數覆蓋,所以您設置的值不可用。
當你調用綁定this這是可用的外部功能,那麼它具有相同的值,你已經設置,見下面糾正的代碼。

let self= this; 
    self.userInfo = 'bla'; 
     request({ 
      url: 'https://api.api.ai/v1/entities?v=20150910', 
      headers : { 
       Authorization: "Bearer " + process.env.APIAI_ACCESS_TOKEN 
      }, 
      method: 'GET' 
     }, function (error, response, body) { 
      if (error) { 
       console.log('Error sending message: ', error); 
      } else if (response.body.error) { 
       console.log('Error: ', response.body.error); 
      } 
    //scope of 'this' in callback function are removed, so have set value to self variable 
      console.log(self.userInfo); 
     }.bind(this)); 
+0

我看功能:)。謝謝 ! – Alessandro

+0

總是歡迎您:) – anomepani