Solitude
Executive Member
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:
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.
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.