节点 - this.func() 不是函数 [英] node - this.func() is not a function
问题描述
function Job(name, cronString, task) {
"use strict";
this.name = name;
this.cronString = cronString;
this.isReady = false;
this.task = task;
}
Job.prototype.performTask = (db, winston) => {
"use strict";
const Promise = require("bluebird");
let that = this;
return new Promise((resolve, reject) => {
let output = "";
let success = true;
try {
output = that.task();
}
catch(error) {
success = false;
reject(error);
}
if(success) {
resolve(output);
}
});
};
module.exports = Job;
这里是 JavaScript 新手.当我创建一个 Job
对象并调用 performTask
方法时,我得到that.task 不是函数".performTask
方法开头的this
不应该引用Job
吗?我犯了什么错误?另外,有没有更好的方法来做我在这里想做的事情?
Javascript newbie here. When I make a Job
object and call the performTask
method, I get "that.task is not a function". Shouldn't this
at the very beginning of the performTask
method refer to Job
?
What is the mistake I'm making?
Also, is there a better way of doing what I'm trying to do here?
推荐答案
我犯了什么错误?
What is the mistake I'm making?
您正在使用箭头函数.this
内部箭头函数的解析方式不同,它不会引用您的 Job
实例.
You are using an arrow function. this
inside arrow functions is resolved differently, it won't refer to your Job
instance.
不要在原型方法中使用箭头函数.
Do not use arrow functions for prototype methods.
查看箭头函数与函数声明/表达式:它们是否等效/可交换?了解更多信息.
这篇关于节点 - this.func() 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!