For the module pattern, I'm doing something like:
(function(namespace) {
// tons of code
// blabla
})(window.myGlobalNamespace);
How do I split the code? I can think of a few ways, like use a hierachy of namespaces, or expand the object outside by window.myGlobalNamespace.additionalFunc = function () {//blabla}
. What are the other ways? What are the pros and cons? Which one is considered better practice?
Both of the two answers suggest RequireJS. Can you please explain how RequireJS can solve these problems:
first.js:
(function(context) {
var parentPrivate = 'parentPrivate';
})(window.myGlobalNamespace);
second.js:
(function(context) {
this.childFunction = console.log('trying to access parent private field: ' + parentPriavte);
}(window.myGlobalNamespace.subNamspace);
main.js:
window.myGlobalNamespace.subNamspace.childFunction(); // doesn't work
And people can do
window.myGlobalNamespace.subNamspace.childFunction = function() {alert("a new function");}
to change my code's behaviour!
Here, there are two problems:
We can't have a field that's accessible by child but not to outside public (i.e. protected). Is there any way to achieve that?
If not, meaning if we wanteparentPrivate to be accessible, we need to make it public. Then the user will be able to modify it!
What's more, all the public functions can be altered and replaced. I don't want that to happen.
I don't see how RequireJS solves these problems. Can someone shed some light?
myFunction
from module B. But, if I makemyFunction
public, doesn't it mean that the client can also alter the function (by doingwindow.B.myFunction = ...
)? How should I solve that problem? AssumingmyFunction
shouldn't be modified and it's critical – Stavros