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?
Modularization (splitting the code) is not the same as data protection (hiding data).
RequireJS solves the modularization issue, not the data-protection issue. Or to put it differently... Whatever issues exist with trying to protect data and whatever solutions exist to protect data, these issues and solutions are the same with or without RequireJS.
RequireJS implements all the mechanics to specify dependencies between modules, to load these dependencies only as needed, to avoid reloading things that have already been loaded, avoid loading things that are not required at all, quickly change the location of modules, have redundancy, etc.
After deployment if one finds RequireJS somehow too heavy, there's the almond library that can be used instead.
If you want modularization (i.e. you want the child to be coded separately from the parent), I do not believe this is possible in JavaScript. It would be possible to have child and parent operate in the same closure but then this would not be modular. This is true with or without RequireJS.
If you want to prevent assigning to
parentPrivate
, you can useObject.freeze()
on the namespace that containsparentPrivate
.However, I don't know how well it is supported by various browsers. And if what is in
parentPrivate
is itself an object rather than a primitive value, it also needs to be frozen if you don't want it to be modified by clients of your code. And once an object is frozen, it is frozen for everyone so the module that owns the object does not get special treatment to modify it. And freezing does not hide anything.Or you could use setters and getters like in this RequireJS example:
If the module is imported as
parent
, thenparent.unwritable
cannot be written to but the module itself can still change the value returned by writing towritable
. Note that if the return value returned by the getter is an object rather than a primitive value, this object can be modified by the caller.Again, this is true whether or not you use RequireJS. The solutions are the same, the problems are same, etc.
There are only 2 ways to get JavaScript into HTML:
<script> some JavaScript </script>
<script src='main.js'></script>
I know this is obvious but we need that common ground for what comes next. ;)
JavaScript does not have the ability to "import" other JavaScript files into it's self. All the "importing" is done in the HTML. You can do this several ways:
Dynamically link them in through some JavaScript
Library like RequireJS. RequireJS uses Asynchronous Module Definition (AMD) API. It is the JavaScript mechanism for defining modules such that the module and its dependencies can be asynchronously loaded.
It is import to consider reasons for separating JavaScript into separate files.
Separate JavaScript files DO NOT make things Private, Closures make things Private.
Now, consider at the end of the day when everything is ready for production the best thing you could do is Optimize your JavaScript by combining it all into one file so that the user only has one file to download.
When dealing with Private variables in JavaScript, you will at some point want to access them.
Let me illustrate with some code.
module-test.html and main.js (merged first.js, second.js, and main.js for easier testing)
If you want to use RequireJS to accomplish the above, you can. RequireJS uses the Module Pattern which is what you and I are already using. If you want to separate out the files then there are two ways to do this.
NOTE: I haven't had a chance to compare these two options yet but wanted to include them for completeness.
You may find the following references helpful:
Protected variables in javascript can be achieved by passing in the protected variables as a dependency. The subclass must be created within the parent as only there does it have access to the protected variables. Example jsFiddle
SubClass.js
main.js
NOTE: as Charles W. mentioned, this pattern only works when
protectedState
is an object. If it were a string/int it would be passed by value and changes made in the subclass would not be visible from the parents copy.It sounds like what you're after is Require JS. I use this in almost all of my builds now. Alternatively you can have a look at the revealing module pattern as a fallback but for what you're after it sounds like Require is much more suitable.
http://requirejs.org
A good read: http://net.tutsplus.com/tutorials/javascript-ajax/principles-of-maintainable-javascript/