Javascript TypeError:无法读取属性';forEach&x27;未定义的

Javascript TypeError:无法读取属性';forEach&x27;未定义的,javascript,node.js,class,Javascript,Node.js,Class,我正在用JavaScript和Nodejs介绍我自己 我用构造函数创建了一个类 在这个构造函数中,cron作业每分钟执行一次 cronjob从定义为类字段的映射中删除条目 class Infos{ static TEN_SECS = 10000; static cron = require('node-cron'); static codeMap = new Map(); static evictionRegisty = new Map(); constructor() { co

我正在用JavaScript和Nodejs介绍我自己

我用构造函数创建了一个类

在这个构造函数中,cron作业每分钟执行一次

cronjob从定义为类字段的映射中删除条目

class Infos{

static TEN_SECS = 10000;

static cron = require('node-cron');

static codeMap = new Map();
static evictionRegisty = new Map();

constructor() {
    console.log('Create repo!');
    //Run each minute
    cron.schedule('* * * * *', function() {
        console.log('Scheduler executed!');
        this.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)
            }
        });
    });
};
cronjob工作正常,将每分钟执行一次。 无论出于何种原因,在调用ReceivingRegistry映射的foreach方法时都会出现异常:

TypeError: Cannot read property 'forEach' of undefined
作为一名Java开发人员,我要说的是,在schedule函数的这个范围内没有映射。但是如果是这样的话,我怎么能访问地图呢


感谢您的帮助

您是对的,您无法访问函数中的变量,因为它超出范围

将变量设置为函数外部的作用域,并在函数内部使用该变量,如下所示:

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)
            }
        });
    });
};

此错误表示“This”对象没有“executionRegistry”字段。这意味着它不是“Infos”类。要解决这个问题,您需要将变量作为输入传递给回调函数,或者在调用“executionregistry”之前简单地松开“this”。 您的循环将是:

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)
   }
}

尝试在调度程序中使用箭头函数而不是匿名函数。这里-->cron.schedule('***',()=>{your code})