[英]scope in call back function in setTimeout() in nodejs 8
我正在使用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.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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.