开发者

Referencing an object to be augmented in javascript

开发者 https://www.devze.com 2022-12-20 01:36 出处:网络
I am trying to localize everything to a namespace in javascript.So I have objects that follow a naming convention like:

I am trying to localize everything to a namespace in javascript. So I have objects that follow a naming convention like:

myapp.utilities.file.spinner

etc...

My question is, is there a way开发者_Python百科 to avoid repeating that big string everytime I want to augment the object with a property or a method. Currently my code looks like this...

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

Something like this...

spinnerPath.method1 = function()

...where spinnerPath stands for myapp.utilities.file.spinner, would be nicer. But from my understanding I cannot just say

spinnerPath = myapp.utilities.file.spinner

as that will create another object in the global space.

Thanks


The code you're using won't actually create a new object, merely a new global variable referring to the existing object. It will pollute the global namespace however, so if you're looking to avoid that, you have several options:

  • You can use with, but don't because it will probably cause you more heartache than it's worth.

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

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

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


Try this:

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

})();


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();


You can just make 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 is in fact a local reference to the global myapp.utilities.file.spinner object, not a copy. Objects in JavaScript are references, so if you create a local variable that points to it, you will not create a copy or pollute the global namespace.

0

精彩评论

暂无评论...
验证码 换一张
取 消