Tuesday, July 24, 2007

Javascript package/public/private method

Perhaps a very uncommon approach to developing web applications that require JavaScript is namespacing your scripts. And how to define a scope (public/private) to the method and variable. This blog introduces a simple singleton pattern for achieving this discipline.

First I define a base JS class which will be included in any page to define a package (or you can call it 'namespace'). See right figure for detail source code.

Second, I will call this method in any JS class - define the package just like java class.
/**
* Copyright(c) 2006-2007 ...
*/
package("FEYA.util");

/**
* This JS is used to define a bunch of util class
*
* @author fzhuang
* @Date July 26, 2007
*/
FEYA.util.common = function(){
// private variable/function. Not accessible from outside
var count = 0;
var increaseCount = function(){count++;};

// Priviledged method. Can be called from outside
return {
formatDate: function(value){
return value ? value.dateFormat('D, M d Y') : '';
}
}
}();
Third, I can call following public functions from any JS class.
FEYA.util.common.formatDate