javascript - 无法在类中使用 this 调用函数

标签 javascript node.js npm

我有一个名为 Scheduler 的类,它使用模块 cron 执行 cron 作业。我创建了一个函数来获取两个日期之间的天数差异,如果我在 cron 作业迭代之外调用该函数,该函数就可以工作,否则它将返回

TypeError: this.getDaysDifference is not a function

这是我的代码:

const CronJob = require('cron').CronJob;

class Scheduler {

    async start() {

        // HERE WORKING
        console.log(this.getDaysDifference(new Date('2020-03-29'), new Date('2020-03-30')));

        const job = new CronJob('0 */1 * * * *', async function () {
            let messages = await MessageModel.find();
            for (const msg of messages) {
                // HERE NOT WORKING
                console.log(this.getDaysDifference(new Date(), msg.lastScheduler));
            }
        });

        job.start();
    }

    getDaysDifference = function(start, end) {
        const _MS_PER_DAY = 1000 * 60 * 60 * 24;
        const utc1 = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
        const utc2 = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
        return Math.floor((utc2 - utc1) / _MS_PER_DAY);
    }
}

exports.Scheduler = Scheduler;

最佳答案

由于您使用了函数,this.getDaysDifference 并未指向回调中 Scheduler 类的实例 .

有两种方法可以解决此问题:

  • 使用非常简单的箭头函数 () => {}

  • 使用 functionObj.bind(yourInstance)this 显式绑定(bind)到您的实例。

您可以使用箭头函数将 this 绑定(bind)到回调定义中的词法 this:

new CronJob('0 */1 * * * *', async () => {
     let messages = await MessageModel.find();
     for (const msg of messages) {
         //this will be the lexical  this i.e. point to the instance o sthe Scheduler class
         console.log(this.getDaysDifference(new Date(), msg.lastScheduler));
        }
});

使用 bind 的解决方案,将 this 的值显式绑定(bind)到类的实例:

let cronJobCallback = async function () {
      let messages = await MessageModel.find();
      for (const msg of messages) {
      // HERE NOT WORKING
      console.log(that.getDaysDifference(new Date(), msg.lastScheduler));
      }
 }
 cronJobCallback = cronJobCallback.bind(this);
 new CronJob('0 */1 * * * *', cronJobCallback);

关于javascript - 无法在类中使用 this 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60914310/

相关文章:

javascript - 如何发布 angular2 指令

node.js - 创建应用程序WebRTC

javascript - 执行 Mongoose 查询后从未调用的回调函数

javascript - 使用 Jquery 或 Javascript 解析字符串

javascript - 元素的宽度在 javascript 中占怪癖模式?

javascript - 单击链接时如何动态获取用户名或详细信息

javascript - Sails.js + Grunt "Cannot find module"错误

node.js - sudo npm install -g Node 检查器错误

node.js - 在 Express js 中无需密码即可检查 Active Directory

javascript - 为生产构建 webpack - 最小化依赖项