2017-08-17 51 views
0

我正在使用nodejs 8和類功能,但發現此綁定是意外的。範圍中的回調函數setTimeout()in nodejs 8

在我的下面的代碼中,應該可以在由setTimeout創建的閉包中訪問xxx變量,但它不是。爲什麼?

class Wechat { 

    constructor(option) { 
    this.option = option 


    } 

    verifySource() { 
    console.log('verify source...') 
    } 

    async setMenu() { 
    console.log('setMenu...') 
    let thisObject = this 
    let nick = 'nick xu' 
    var xxxx = 'xxxx nick xu' 
    let accessToken = await this.getAccessToken() 
    console.log('accessToken:', accessToken) 
    setTimeout(function() { 
     // let abc = await thisObject.getAccessToken() 
     // no access to xxxx and nick variables 
     // this point to Timeout object 
     console.log('2nd time token:', '000000') 
    }, 5000) 
    return Promise.resolve(33) 
    } 




    async getAccessToken() { 
    /* 
    this.access_token = 'kkkkkk' 
    this.expires_in = 7200 
    this.access_token_receive_time = 123456 
    */ 
    const timeBuffer = 60 * 10 * 1000 // 10 min 
    if (this.access_token && this.expires_in && this.access_token_receive_time) { 
     // if any of the above data exist 
     // check expire 
     let currentTime = new Date().getTime() 
     if (currentTime - this.access_token_receive_time > timeBuffer + this.expires_in * 1000) { 
     // token is valid 

     return this.access_token 
     } 
    } 

    let result = await rp.get(config.baseUrl + '/token?' + 
     'grant_type=client_credential&appid=' + config.appID + 
     '&secret=' + config.appSecret) 
    let resultJson = JSON.parse(result) 
    console.log('result of token request:', result) 
    this.access_token = resultJson.access_token 
    this.expires_in = resultJson.expires_in 
    this.access_token_receive_time = new Date().getTime() 
    return this.access_token 

    } 

    static distance() { 
    console.log('static method distance') 
    } 
} 

當在調試裏面的setTimeout回調。 enter image description here

此指向超時。到底是怎麼回事? enter image description here

檢查觀察者,XXXX和尼克都無法使用...... enter image description here

+1

你似乎在這裏問兩個不相關的事情。在控制檯中,您正在檢查'this',但'xxxx'和'nick'變量與'this'無關,它們是'setMenu()'中的局部變量。 – nnnnnn

+0

在setTimeout回調中,xxxx和nick變量應該可用,因爲它們在外部閉包中。它是否正確? –

+1

是的。你是如何嘗試使用它們的?顯示的代碼中沒有任何內容試圖使用它們。 – nnnnnn

回答

-1

如果你只是想綁定正確的「這

setTimeout.call(this, function(){}) //or put whatever scope you want for this

,如果你想在settimeout中添加參數,你可以使用這個

let thisObject = this 
 
    let nick = 'nick xu' 
 
    var xxxx = 'xxxx nick xu' 
 
    
 
    setTimeout (function (thisObject,nick,xxxx) {},1000,thisObject,nick,xxxx);

+0

這就是* not *如何在回調中綁定'this'的值,即爲'setTimeout()'本身設置'this'的值(這將導致錯誤,除非第一個參數爲'.call )'是全局對象)。 – nnnnnn