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')
}
}
你似乎在這裏問兩個不相關的事情。在控制檯中,您正在檢查'this',但'xxxx'和'nick'變量與'this'無關,它們是'setMenu()'中的局部變量。 – nnnnnn
在setTimeout回調中,xxxx和nick變量應該可用,因爲它們在外部閉包中。它是否正確? –
是的。你是如何嘗試使用它們的?顯示的代碼中沒有任何內容試圖使用它們。 – nnnnnn