node - this.func() is not a function

佐手、 提交于 2021-01-27 19:31:32

问题


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 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?


回答1:


What is the mistake I'm making?

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.

Have a look at Arrow function vs function declaration / expressions: Are they equivalent / exchangeable? for more information.



来源:https://stackoverflow.com/questions/37120640/node-this-func-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!