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 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: