I have three js files in my project and there are around 15 functions repeated in each file. They are sort of utility functions. To avoid this repetition, I used $.extend :
$.extend({
myFunction1 : function(){},
myFunction2 : funciton(){},...and so on
});
This approach worked perfectly and I was able to call $.myFunction1() anywhere in the js file.
But, I wanted to create an object that contains all these utility functions. So my other approach was like
MyApp = {
myFunction1 : function(){},
myFunction2 : funciton(){}, ... and so on
}
And I was able to call MyApp.myFunction1() anywhere in the 3 files as MyApp is a global variable.
But I do not want to make it a global variable. All I want is I could call $.MyApp.myFunction1() anywhere in my code. Is there a way to do it?
As far as I can see the only sensible option is a global object. If you want to access something from anywhere it needs to be global.
If you look at most utility libraries e.g http://underscorejs.org/ you will see the same thing. They use a global namespace (similar to your MyApp object) which is just named '_'.
If you try to add the functions to each object individually you will be duplicating them in memory for each object which is a waste.