我有一个名为 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/