08 November 2008

Static Method & Attribute in JavaScript Class

Static methods in a class can be (and is) accessed without creating any object of that class. The static methods is called like Class.staticMethod() style.

As expected, JavaScript does not have any keyword like 'static'. But fortunately, this purpose can be served. Normal methods are defined inside class or using prototype. Static methods have to be defined outside the class and without prototype property.

Here a class TemperatureConverter has 2 static methods celsiusToFahrenheit (converts temperature in celcius to that in fahrenheit ) and fahrenheitToCelsius (opposite of previous function).


// define class
function TemperatureConverter()

{
}

//define static method
TemperatureConverter.celsiusToFahrenheit = function(celsius)
{
return (celsius * 9 / 5) + 32;
}

//define static method
TemperatureConverter.fahrenheitToCelsius = function(fahrenheit)
{
return (fahrenheit - 32) * 5 / 9;
}


Example:
var f = TemperatureConverter.celsiusToFahrenheit(35);
alert("35 degree celcius = " + f +" degree fahrenheit.");

var c = TemperatureConverter.fahrenheitToCelsius(98.4);
alert("98.4 degree fahrenheit = "+ c + " degree celcius.");


Static attributes can be added in similar fashion.
TemperatureConverter.description = "A class that converts temperature between celcius and fahrenheit";

0 Comments:

 

© 2007 t!ps n tr!cks: Static Method & Attribute in JavaScript Class



Template unik dari rohman


---[[ Skip to top ]]---