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
            }
        }
    }
}());
andymurd
  • 821
  • 8
  • 10

1 Answers1

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;
    };
}());
Vadim Baryshev
  • 25,689
  • 4
  • 56
  • 48
  • 1
    I use a `var _public = {};` and `var _privat = {};` and return the `_public`, which adds some readability. – K.. Aug 23 '12 at 12:27
  • What does the "use strict" do here, btw? – d11wtq Aug 23 '12 at 12:31
  • 1
    @d11wtq "use strict" is a new flag for ECMA Script 5 that helps catch a few errors. More at http://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it – andymurd Aug 27 '12 at 06:28
  • 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. – nha Oct 01 '14 at 18:51