【问题标题】:node - this.func() is not a functionnode - this.func() 不是函数
【发布时间】:2016-05-09 16:15:59
【问题描述】:
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 node.js scope prototype this


【解决方案1】:

我犯了什么错误?

您正在使用箭头函数。 this 内部箭头函数的解析方式不同,它不会引用您的 Job 实例。

不要对原型方法使用箭头函数。

查看Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? 了解更多信息。

【讨论】:

    猜你喜欢
    • 2018-03-03
    • 2022-01-25
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    • 2020-04-05
    • 2015-10-27
    • 1970-01-01
    相关资源
    最近更新 更多