【问题标题】:Unable to call a local function on ExpressJS无法在 ExpressJS 上调用本地函数
【发布时间】:2022-02-14 17:12:54
【问题描述】:

我正在学习使用 NodeJs 和 Express JS 开发一个 Rest API。我构建了一个控制器来在其中做我的事情。我想在控制器内部调用一个本地函数,但它不起作用。我总是得到未定义错误。

听到是我的控制器,

const db = require('../config/db');

class TransactionController {

    constructor(){
    }
    
    generateCustomerTransaction(req, res) {

        const program_id = req.params.program_id;

        const customerList = getCustomerList(program_id); //error here

        //Do some business logics

        return res.json(result);
    };


    getCustomerList(program_id) {
       //Do some query to get a list of result
       return results;
    }
}

module.exports = SeatExcelController;

一切看起来都像其他语言一样简单,但我明白

ReferenceError:getCustomerList 未定义

我不知道如何简单地调用本地函数。

请帮忙。非常感谢。

【问题讨论】:

  • 导出时您使用了错误的类名。请改用TransactionController
  • const customerList = getCustomerList(program_id); 更改为const customerList = this.getCustomerList(program_id);。在 Javascript 中,调用方法时必须引用对象。如果您希望引用的对象是您当前在一个方法中的对象,那么您使用this 作为对象引用。在您的示例中,您还必须确保generateCustomerTransaction() 的调用方式对this 具有适当的值。您没有说明需要我们就这部分提供建议的地方。
  • 我注意到您显示的所有方法都没有引用任何实例数据,因此类上的实例方法在这里可能不是合适的工具。也许它们应该是类上的静态方法或只是普通函数。
  • 另外,getCustomerList() 不是本地函数。这是在您的类上定义的方法。它的范围是这样的,它通常仅在该类的实例的上下文中可用。因此,您通常会使用该类的一个实例,然后在该实例上引用该方法。所以,请不要认为这些只是具有正常功能范围的正常功能。他们不是。如果您想以这种方式使用它们,可以将它们定义为普通函数。

标签: node.js express


【解决方案1】:

为了能够以这种方式访问​​您的函数,它需要在类之外的包范围内定义,如下所示:

const db = require('../config/db');

const getCustomerList(program_id) = () => {
   // Do some query to get a list of result
   return results;
}

class TransactionController {
    
    generateCustomerTransaction(req, res) {
        const program_id = req.params.program_id;
        const customerList = getCustomerList(program_id); //error here
        //Do some business logics
        return res.json(result);
    };
}

module.exports = SeatExcelController;

或者在调用之前使用this 调用您的函数,如下所示:

const db = require('../config/db');

class TransactionController {
    
    generateCustomerTransaction(req, res) {
        const program_id = req.params.program_id;
        const customerList = this.getCustomerList(program_id); //error here
        //Do some business logics
        return res.json(result);
    };

    function getCustomerList(program_id) {
        // Do some query to get a list of result
        return results;
    }
}

module.exports = SeatExcelController;

如果函数不需要访问任何类变量,我会选择第一个选项。

【讨论】:

    【解决方案2】:

    如果它与类无关,您也可以将其设为静态函数:

    static getCustomerList(program_id) {
       //Do some query to get a list of result
       return results;
    }
    

    然后像这样调用函数:

    TransactionController.getCustomerList(program_id)
    

    或者只是使用 this 关键字调用函数。因为你现在编码的方式,函数是属于你的类和类依赖的。 :this.getCustomerList(program_id)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      相关资源
      最近更新 更多