Static member functions in javascript
Facts - HTML and Javascript
Friday, 16 October 2009 20:43

How to define and use Static functions in javascript:

  • Define the object,
  • the define the static functions after the object definition

Example:

// Step 1: define the object (Calendar)
function Calendar(currentYear) {
  // define non-static members: variables and functions ...
  // note the use of a static member
  this.currentYear = arguments.length==1 ? Calendar.yearZero +currentYear : Calendar.yearZero;
 
  // static members defined below can be used inside the member functions as well
  this.compareYear = function(ayear)
  {
    return
      (new Number(ayear) +Calendar.yearZero > this.currentYear) && Calendar.validateYear(ayear)
      ? 1 :-1;
  };
}
 
// Step 2: define static member variables and functions
 
Calendar.yearZero=new Number(0);
 
// Note that a static function should not use non static members
Calendar.validateYear = function(testYear)
{
  if (testYear < Calendar.yearZero) return false;
  // more tests ...
  return true;
};
 
// use static members:
 
 // should show false
alert('Validation of year -1: ' +Calendar.validateYear(-1));
var thisYear = new Calendar(2009);
 
// should show 1
alert('Comparison with year 2010: ' +thisYear.compareYear(2010));
 
// the following is undefined:
// static members should be accessed via the object name, not via the instance name
alert('Property yearZero of instance thisYear of object Calendar: ' +thisYear.yearZero);