JavaScript Namespace
Blogs20142014-04-12
JavaScript Namespace
<script>
(function($) {
// Define functions, objects etc.
var obj = {};
var ary = [];
function ConstractorFunction() {}
ConstractorFunction.prototype = ...;
var cf = new ConstractorFunction();
...
// When Document is Ready:
$(function() {
}();
}(jQuery));
</script>It is better than without the β(function(){})()β scope, because it make the scripts is in a private scopes. If in a MVC structure, there are different JS files to be used, where Model, View, Controller need to share some global variables, the above β(function(){})()β will not work. Hoverver, by using namespace, this is very easy to solve, like this:
//1. in model.js:
<script>
var app = app || {};
(function() {
...
})();
</script>
//2. in controller.js:
<script>
var app = app || {};
(function() {
...
})();
</script>
//3. in view.js:
<script>
var app = app || {};
(function($) {
...
})(jQuery);
</script>
// 4. Entry (probably in index.html):
<script>
var app = app || {};
$(function($) {
// the global namespace 'app' is accessible
//app.model...
//app.controller...
//app.view...
})(jQuery);
</script>In this way, only βappβ is exposed to global, and different js files can operate βappβ in common. Very clean codes.
