8

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

1 Answer 1

9

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

4 Comments

I use a var _public = {}; and var _privat = {}; and return the _public, which adds some readability.
What does the "use strict" do here, btw?
@d11wtq "use strict" is a new flag for ECMA Script 5 that helps catch a few errors. More at stackoverflow.com/questions/1335851/…
There are many ways to do it, but I like this one : it is readable, allows exporting and referencing methods in the same file, and has clear encapsulation. For debugging purposes though, I personally name my functions.

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.