How to call function A from function B within the same namespace?

javascript

Solution

I recommend placing the "namespace" inside a function scope. Everything not explicitly public will be naturally private:

var Namespace = (function() {
    var self = {};

    // Private
    var A = function() {
        ...
    };

    // Public
    self.B = function() {
        A();
    }

    return self;
}());

Namespace.B(); // Works
Namespace.A(); // Doesn't work

Problem

Let's say I have the namespace, ``` var Namespace = { A : function() { alert('Hello!'); }, B : function() { // Call A() from here, do other stuff } } ``` In this namespace, I intend for A to be a helper function to B. That is to say, A() will never be called outside the namespace. It will only be called by the functions within the namespace. What's the best way to address the issue of a local/helper function within a namespace? The way I see it there are two possibilities: ``` // Method #1 var Namespace = { A: function() { alert('Method #1'); }, B : function() { Namespace.A(); } } Namespace.B(); // Method #2 function Namespace2() { var A = function() { alert('Method #2'); }; this.B = function() { A(); } } var ns2 = new Namespace2(); ns2.B(); ``` In the first method, it is ugly and awkard to type Namespace.A() (repeatedly) in every function within the namespace. This leads me to prefer Method #2. But I was curious what was the best practice here.

Original source