Link to object to be enlarged in javascript

I am trying to localize everything in a namespace in javascript. Therefore, I have objects that follow the naming convention:

myapp.utilities.file.spinner

etc...

My question is, is there a way to avoid repeating this big line every time I want to enlarge an object using a property or method. Currently, my code looks like this ...

myapp.utilities.file.spinner.method1 = function() { }; myapp.utilities.file.spinner.method2 = function() { }; etc. 

Something like that...

 spinnerPath.method1 = function() 

... where spinnerPath means myapp.utilities.file.spinner , it would be better. But from my understanding I can’t just say

 spinnerPath = myapp.utilities.file.spinner 

as this will create another object in global space.

thanks

+4
source share
4 answers

The code you use does not actually create a new object, but simply a new global variable that refers to an existing object. However, it will pollute the global namespace, so if you want to avoid this, you have several options:

  • You can use with , but not because it is likely to hurt you than it costs.

  • You can make a shorthand pointer variable inside each function outside the global namespace: var s = myapp.utilities.file.spinner; but it is annoying.

  • (Probably the best option) create a "private namespace" using the immediate call function:

     (function (S) { S.method1 = function(){/*whatever*/}; S.method2 = function(){/*whatever*/}; })(myapp.utilities.file.spinner) 
+4
source

Try the following:

 (function(){ var spinner = myapp.utilities.file.spinner; spinner.method1 = function(){}; })(); 
+1
source

You can simply create a temporary local variable wrapped in an anonymous function:

 (function(){ var spinnerPath = myapp.utilities.file.spinner; spinnerPath.method1 = function() { }; spinnerPath.method2 = function() { }; spinnerPath.method1(); })(); 

Here spinnerPath actually a local reference for the global object myapp.utilities.file.spinner , and not for the copy. Objects in JavaScript are references, so if you create a local variable pointing to it, you will not create a copy or pollute the global namespace.

0
source
 myapp.utilities.file.spinner.method1 = function() { }; myapp.utilities.file.spinner.method2 = function() { }; ... // Somewhere else in your code, create a temp local called "spinner" // that references your longer path object. var spinner = myapp.utilities.file.spinner; spinner.method1(); 
0
source

Source: https://habr.com/ru/post/1301386/


All Articles