我正在使用nodejs 8和类功能,但发现此绑定是意外的。
在我的下面的代码中,xxx变量应该可以在setTimeout创建的闭包中访问,但事实并非如此。为什么?
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')
}
}
答案 0 :(得分:-1)
如果你只想绑定正确的"这个
// Construct a string to hold the whole args.
// Implemented it this way because args is separated by spaces
String combine = "";
for(int i = 0; i < args.length; i++)
{
combine = combine.concat(args[i]);
combine = combine.concat(" ");
}
System.out.println(combine);
&#13;
如果你想在settimeout中添加参数,你可以使用这个
setTimeout.call(this, function(){}) //or put whatever scope you want for this
&#13;