Wednesday, December 8, 2010

JavaScript: Namespaces

http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/

The section on using this as a namespace proxy is brilliant. The origin of that idea is here (James Edwards).

Example:
var myApp = {};
(function() {
var id = 0;

this.next = function() {
return id++;
};

this.reset = function() {
id = 0;
}
}).apply(myApp)

window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next()
) //0, 1, undefined, 0
or more powerfully

var subsys1 = {}, subsys2 = {};
var nextIdMod = function(startId) {
var id = startId || 0;

this.next = function() {
return id++;
};

this.reset = function() {
id = 0;
}
};

nextIdMod.call(subsys1);
nextIdMod.call(subsys2,1000);

window.console && console.log(
subsys1.next(),
subsys1.next(),
subsys2.next(),
subsys1.reset(),
subsys2.next(),
subsys1.next()
) //0, 1, 1000, undefined, 1001, 0

1 comment:

  1. See also:

    * http://www.commonjs.org/
    * http://www.sitepen.com/blog/2010/03/29/understanding-dojo-require/

    ReplyDelete