Javascript Namespace

Solitude

Executive Member
Joined
Jul 23, 2008
Messages
8,438
Reaction score
5,147
Location
Little Falls
I'm a c++/c# developer and mostly do backend development.

For a change I'm playing around with javascript today and even though it's familiar it's still a wee bit different to what I'm used to.

So I've got a question about using a namespace in js. First a code example:

Code:
var MyNS = MyNS || {};
MyNS.Current = 0;
MyNS.arrayA = {
	0: { id: 101, name: 'Bob', next: 2 },
	1: { id: 32, name: 'Jake', next: 0 },
	2: { id: 86, name: 'Julie', next: 1 }
};
MyNS.DoSomethingA = function () {
	$('#labelA').text(MyNS.arrayA[MyNS.Current].name);
	MyNS.Current = MyNS.arrayA[MyNs.Current].next;
}
MyNS.DoSomethingB = function () {
	var arr = MyNS.arrayA;
	var cur = MyNS.Current;
	$('#labelA').text(arr[cur].name);
	MyNS.Current = arr[cur].next;
}

$('#testButtonA').click(MyNS.DoSomethingA);
$('#testButtonB').click(MyNS.DoSomethingB);

As you can see I'm just playing around and I've got two functions DoSomethingA and DoSomethingB, both doing the same thing. The reason they are both doing the same thing is because I'm looking for an elegant way to write the code.

My problem is that I don't want to go and add MyNS in front of everything inside the function. Is there a more elegant way of using a namespace? It's probably something simple since I know very little of js to be honest.
 
You might want to look into classes which you then namespace
 
myNS = {

doSomethingA : function() { _ = this;

...
},

doSomethingB : function() { _ = this;

_.doSomethingA;

},



}
 
You can use an IIFE (Immediately Invoked Function Expression), see code below.
Code:
var myNamespace = myNamespace || {};

(function(ns) {
    ns.doSomethingOne = function() {
        //Do stuff here
    };

    ns.doSomethingTwo = function(varA, varB, varEtc) {
        //Do stuff here
    };

})(myNamespace);
and to use it:
Code:
myNamespace.doSomethingOne();

This might not look useful now, but I seldom have a one word namespace.
This is generally more the way I use it.
Code:
var myNamespace = myNamespace || {};
myNamespace.something = myNamespace.something || {};
myNamespace.something.somethingElse = myNamespace.something.somethingElse || {};

(function(ns) {

    ns.functionOne = function () {

    };

})(myNamespace.something.somethingElse);
 
Last edited:
Top
Sign up to the MyBroadband newsletter
X