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

Say I have a namespace,

var Namespace = { A : function() { alert('Hello!'); }, B : function() { // Call A() from here, do other stuff } } 

In this namespace, I intend to use A as a helper function for B. That is, A () will never be called outside the namespace. It will only be called by functions inside the namespace.

What is the best way to solve a local / helper function problem in a namespace? I see that 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 each function in the namespace. This makes me prefer Method No. 2. But I was curious what the best practice was here.

+7
javascript
source share
5 answers

I recommend putting the "namespace" inside the function area. Everything that is clearly not open will be natural:

 var Namespace = (function() { var self = {}; // Private var A = function() { ... }; // Public self.B = function() { A(); } return self; }()); Namespace.B(); // Works Namespace.A(); // Doesn't work 
+10
source share

You can call it using the this operator

 this.A(); 
+5
source share

Well, you can use the third option, where the namespace is created in its own area:

 var Namespace = (function(){ var A = function() { alert('scoped method'); }; function Namespace() { var A1 = function() { alert('Namespace "private" method'); }; Namespace.prototype.B1 = function(){ A(); //will run A1(); //will run with no errors }; }; Namespace.prototype.B = function(){ A(); //will run A1(); //ERROR! }; return Namespace; })(); 
+2
source share

If you are only going to use A inside B , why not define it inside B ?

 var Namespace = { B: function() { var A = function() { ... } A(); } }; Namespace.B(); 
+1
source share
 var Namespace = { A : function() { alert('Hello!'); }, B : function() { Namespace.A(); }, } 

pay attention to a half in the end

-2
source share

All Articles