andymurd
andymurd

Reputation: 821

Node.js: Calling one exported function from another in the same module

I am writing a node.js module that exports two functions and I want to call one function from the other but I see an undefined reference error.

Is there a pattern to do this? Do I just make a private function and wrap it?

Here's some example code:

(function() {
    "use strict";

    module.exports = function (params) {
        return {
            funcA: function() {
                console.log('funcA');
            },
            funcB: function() {
                funcA(); // ReferenceError: funcA is not defined
            }
        }
    }
}());

Upvotes: 8

Views: 7995

Answers (1)

Vadim Baryshev
Vadim Baryshev

Reputation: 26189

I like this way:

(function() {
    "use strict";

    module.exports = function (params) {
        var methods = {};

        methods.funcA = function() {
            console.log('funcA');
        };

        methods.funcB = function() {
            methods.funcA();
        };

        return methods;
    };
}());

Upvotes: 9

Related Questions