2 回答

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
你是對(duì)的,你無(wú)法訪(fǎng)問(wèn)函數(shù)內(nèi)的變量,因?yàn)樗隽朔秶?/p>
設(shè)置一個(gè)等于函數(shù)外部范圍的變量,并在函數(shù)內(nèi)使用它,如下所示:
class Infos{
static TEN_SECS = 10000;
static cron = require('node-cron');
static codeMap = new Map();
static evictionRegisty = new Map();
var root = this;
constructor() {
console.log('Create repo!');
//Run each minute
cron.schedule('* * * * *', function() {
console.log('Scheduler executed!');
root.evictionRegisty.forEach((key, value, map) => {
if (key > Date.now() - TEN_SECS){
this.codeMap.delete(value);
this.evictionRegisty.delete(key);
console.log('Remove k/v =' + key + '/'+ value)
}
});
});
};

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
此錯(cuò)誤意味著“this”對(duì)象沒(méi)有“evictionRegisty”字段。這意味著它不是“Infos”類(lèi)。為了解決這個(gè)問(wèn)題,您需要將變量作為輸入傳遞給回調(diào)函數(shù),或者在調(diào)用“evictionRegisty”之前簡(jiǎn)單地釋放“this”。你的循環(huán)將是:
evictionRegisty.forEach((key, value, map) => {
if (key > Date.now() - TEN_SECS){
this.codeMap.delete(value);
this.evictionRegisty.delete(key);
console.log('Remove k/v =' + key + '/'+ value)
}
}
添加回答
舉報(bào)