garenyondem garenyondem - 3 months ago 15
Node.js Question

Function inside object is not a function

this is my object

var Controller = (function () {
var self = this;
self.get = function (req, res) {
res.send({
success: 'you got me'
});
}
return self;
})()
module.exports = Controller;


and below is how i am trying to pass parameters to the get function from another document.

var Controller = require('../Controller.js');
Controller.get(arg1, arg2);


However nodejs throws 'TypeError: Controller.get is not a function', what am i doing wrong here? Thanks

Answer

There are several issues with that code, but it will not cause the TypeError: Controller.get is not a function you describe.

The way you're calling your anonymous function that creates Controller means that this within it will be the global object (loose mode) or undefined (strict mode). Let's assume loose mode as you haven't said you're getting an error assigning get to undefined. That means you're creating a global function called get. It also means that Controller returns the global object.

Neither of those is a good thing. :-)

If you want to export an object with a get function, you don't need to do anything nearly so complicated:

var Controller = {
    get: function (req, res) {
        res.send({
            success: 'you got me'
        });
    }
};
module.exports = Controller;

Or perhaps

function get() {
    res.send({
        success: 'you got me'
    });
}

module.exports = { get: get };

Since this is in the context of a NodeJS module, that doesn't define a global function (modules are called in a private scope).


Or, if you meant Controller to be a constructor, then you need to call it via new and reorganize it slightly:

function Controller() {
    var self = this; // If you need it for something, you don't in your example
    self.get = function get() {
        res.send({
            success: 'you got me'
        });
    };
}

module.exports = Controller;

then use it via new:

var Controller = require('./.Controller.js');

var c = new Controller();
c.get("foo", "bar");

It's also probably worth pointing out that require('../Controller.js') uses the Controller.js file from the parent directory, not the current directory. Just in case that wasn't on purpose and you're getting the TypeError: Controller.get is not a function because you're getting the wrong file.

Comments