2

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.

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that was a dumb mistake. Editing your answer to show exactly what I should have done for others who make the same stupid mistake.
1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.