Avoiding namespace duplication in Javascript

I am working on a basic application.

I structured my models + collections + views in different files.

which means a solution of type function() { // all my code }() does not apply here

I added a namespace, for example. App.ModelName App.Views.ViewName etc.

when I enter the same namespace. How can I avoid repeating this. ie how can I call ModelName when I have a function defined in App.Views.ViewName

I am currently repeating the full line ie App.XXXX

thanks

+4
source share
3 answers

You have several options:

1) Create a local variable in each function:

 App.ModelName.myFunction = function() { var model = App.ModelName; // then you can reference just model model.myFunction2(); } 

2) Create a local variable in each area of โ€‹โ€‹the file:

 (function() { var model = App.ModelName; model.myFunction = function() { // then you can reference just model model.myFunction2(); } // other functions here })(); 

3) Use the value of this :

 App.ModelName.myFunction = function() { // call App.ModelName.myFunction2() if myFunction() was called normally this.myFunction2(); } 
+5
source

A namespace is just an object within a global scope.

Thus, one option is to use with , although it has some disadvantages.

But anyway, check out this example:

 window.test = { a: function(){ console.log(this); return 'x'; }, b: function(){ with (this){ alert(a()); }} // <- specifying (this) }; window.test.b(); 
+2
source

How to pass them as arguments? Something like that:

 (function(aM,aV) { // use aM and aV internally })(App.Models,App.Views); 
+1
source

All Articles