最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - module.exports function undefined when passing in a variable - Stack Overflow

programmeradmin3浏览0评论

In my Node.js app, I'm passing in variables to functions by using require like so:

console.log(require('../controllers/controller')(variable)); // undefined

However, when I don't pass in the variable, it logs as a function, like so:

console.log(require('../controllers/controller')); // [Function]

My controllers are defined like this:

var Controller = function (variable) {
  this.variable = variable;
};

Controller.prototype.method = function (someInput, callback) {
  // can access this.variable;
};

module.exports = Controller;

I also get this error:

TypeError: Object function (variable) {
  this.variable = variable;
} has no method 'method'

Any idea as to where I'm going wrong here? I'm stuck at this step and not sure how to debug further.

In my Node.js app, I'm passing in variables to functions by using require like so:

console.log(require('../controllers/controller')(variable)); // undefined

However, when I don't pass in the variable, it logs as a function, like so:

console.log(require('../controllers/controller')); // [Function]

My controllers are defined like this:

var Controller = function (variable) {
  this.variable = variable;
};

Controller.prototype.method = function (someInput, callback) {
  // can access this.variable;
};

module.exports = Controller;

I also get this error:

TypeError: Object function (variable) {
  this.variable = variable;
} has no method 'method'

Any idea as to where I'm going wrong here? I'm stuck at this step and not sure how to debug further.

Share edited Jan 11, 2012 at 20:53 Josh Smith asked Jan 11, 2012 at 20:47 Josh SmithJosh Smith 15k19 gold badges73 silver badges125 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

require('../controllers/controller') is a function. When you use it without new keyword it does not return anything. But when you use new function() it acts like a constuctor of the object. So what you want to do is to use new keyword if you need an object to be returned with its prototype methods.

var Controller = require('../controllers/controller'),
controller = new Controller(variable);

this is an old thread, but I had this issue and the accepted answer didn't help me.

To create a module with a parameter, I use this code:

module.exports = function(pName) {
  return {
    test1: function() {
       console.log('In test 1 '+pName);
    },
    test2: function() {
       console.log('In test 2 '+pName);
    }
  };
};

And to call the module's functions:

var testModule = require('testModule')('David');
testModule.test1();
testModule.test2();
发布评论

评论列表(0)

  1. 暂无评论