Warm tip: This article is reproduced from serverfault.com, please click

Node JS call a "local" function within module.exports

发布于 2015-10-12 10:32:34

How do you call a function from within another function in a module.exports declaration?

I have MVC structure node js project and a controller called TestController.js. I want to access method within controller, but using this keyword gives below error:

cannot call method getName of undefined

"use strict"
module.exports = {
    myName : function(req, res, next) {
        // accessing method within controller
        this.getName(data);
    },

    getName : function(data) {
        // code
    }
}

How do I access methods within controller?

Questioner
sravis
Viewed
0
sravis 2015-10-12 20:00:40

I found the solution :-)

"use strict"
var self = module.exports = {
    myName : function(req, res, next) {
        // accessing method within controller
        self.getName(data);
    },

    getName : function(data) {
        // code
    }
}