传入variables时,module.exports函数未定义
在我的Node.js应用程序中,我通过使用require
来传递variables到函数,如下所示:
console.log(require('../controllers/controller')(variable)); // undefined
但是,当我不传入variables时,它会logging一个函数,如下所示:
console.log(require('../controllers/controller')); // [Function]
我的控制器是这样定义的:
var Controller = function (variable) { this.variable = variable; }; Controller.prototype.method = function (someInput, callback) { // can access this.variable; }; module.exports = Controller;
我也得到这个错误:
TypeError: Object function (variable) { this.variable = variable; } has no method 'method'
任何想法,我要去哪里错了? 我被困在这一步,不知道如何进一步debugging。
require('../controllers/controller')
是一个函数。 当你使用它没有new
关键字,它不会返回任何东西。 但是当你使用new function()
它就像对象的构造new function()
一样。 所以你想要做的就是使用new
关键字,如果你需要一个对象的原型方法返回。
var Controller = require('../controllers/controller'), controller = new Controller(variable);
这是一个古老的线程,但我有这个问题,接受的答案没有帮助我。
要创build一个带有参数的模块,我使用下面的代码:
module.exports = function(pName) { return { test1: function() { console.log('In test 1 '+pName); }, test2: function() { console.log('In test 2 '+pName); } }; };
并调用模块的function:
var testModule = require('testModule')('David'); testModule.test1(); testModule.test2();