18 November 2008

Floating Point Precision in JavaScript

There is an unusual-named function in JavaScript for floating point precision - toFixed. I am really surprised at this naming.

Function singnature:
string toFixed (noOfdigit)

Example:

var n = 3.7345;
var n1 = n.toFixed(2); // n1 = 3.73
var n2 = n.toFixed(3); // n2 = 3.735


Note: toFixed function return a string, NOT a number. So, to get a number, you have to use parseFloat function. For example,

var
n1 = parseFloat( n.toFixed(2) ) ;

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";

Detect Browser Window Size from JavaScript

Web programmers often require to know the browser window size. But as different browsers have different properties for this purpose, programmers get annoyed. Following code is for such programmers to make their lives easy.


function getBrowserWindowSize()
{
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' )
{
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
}
else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
{
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
{
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}

return {width:myWidth, height:myHeight};
}


Example:
var browserWindowSize = getBrowserWindowSize();
alert("width: "+
browserWindowSize.width + " height: " + browserWindowSize.height);

07 November 2008

Interface in JavaScript

Interface contains the method signature only. No method is implemented here, all are abstract. The class(es) must implement the methods to work properly.

In JavaScript, interface concept is absent. But for the sake of well-design of project, we should follow the concept in some way.

Concept behind Interface Implementation:

  • Interface will be a super class.
  • A class will extend Interface.
  • Then the class will override the methods in Interface.
  • If by error, the methods are not overridden, then the method of Interface will be called from where an Exception is thrown. So, to stay away from exception, developer must override the methods. In this way, Interface comes in action.
Here we will develop an Interface UI. There are 2 methods in UI - draw(width,height) and remove(). A classe Button will implement UI.


function UI()
{

this.draw = function(width, height)

{
throw "You must implement draw function";

}

this.remove = function()

{
throw "You must implement remove function";

}

}



Button.prototype = new UI;
function Button(text)
{

this._text = text;

this.button = null;

this.draw = function(width, height)
{
this.button = document.createElement("input");
this.button.setAttribute("type","button");
this.button.setAttribute("value",this._text);
this.button.style.width = width + "px";
this.button.style.height = height + "px";
document.body.appendChild(this.button);
}

this.remove = function()
{
if (this.button != null)
{
document.body.removeChild(this.button);
this.button = null;
}
}


}

OOP in JavaScript : Inheritance

There is no direct keyword (like 'extends' in Java) in JavaScript for inheritance. But its purpose can be served through 'prototype' attribute. Here, firstly an sample code is shown and then related points are described.

Sample Code of Inheritance:


function SuperClass(name)
{
this._name = name;

this.getName = function()
{

return this._name;

}
}


// inheritance occurs here

SubClass.prototype = new SuperClass;
function SubClass(name, address)
{

// calling constructor of super class

SuperClass.call(this,name);

//new attributes

this._address = address;

this.getAddress = function()

{
return this._address;

}
}




Object Creation & Usage:
Please observe the following code.

var sub = new SubClass("Alor Chhota","Mohammadpur");

alert("Name: " + sub.getName());
alert("Address: " + sub.getAddress());



Extending Super Class in Sub Class:
The following command asks to extend SuperClass in SubClass.
SubClass.prototype = new SuperClass;

Passing Parameters to SuperClass Constructor:
If you see the above code, you'll find the following line -
SuperClass.call(this,name);

This is actually the call of SuperClass constructor. Look closely at the sent parameters. The first parameter must be 'this' (SubClass) and the parameters of SuperClass will follow it. More descriptively, 2nd paramter of 'call' function is actually the 1st parameter of SuperClass, 3rd of call is 2nd of SuperClass etc.

OOP in JavaScript : Class

The OOP (Object Oriented Programming) concept is really poor in JavaScript. Fortunately, it supports class concept, although the keyword 'class' is not used. 'function' keyword serves the purpose of 'class'. There are several ways to implement class. Here I'm showing the simplest one (in my opinion).

Creating Class:
The following code creates a Person class with 4 attributes[ name, father, mother & address] and 2 methods [getName() & setAddress(address)].


function Person(name, father, mother, address)
{
this._name = name;
this._father = father;
this._mother = mother;
this._address = address;

this.getName = function()
{
return this._name;
}

this.setAddress = function(address)
{
this._address = address;
}

}

Note:
  • The attributes are created and accessed through 'this' keyword.
  • Person function is the constructor of the class which takes 4 parameters.
  • The constructor (or function) can't be overloaded like C++ or Java.

Creating Instance (Object):
It's simple enough to understand from the following code.

var p1 = new Person("Ahona Saha", "Anup Kumar", "Snigdha Saha", "Bogra");
var p2 = new Person("Ananyo Mounota", "Asim Kumar Saha", "Aparna Saha", "Narsingdi");



Accessing Attributes and Calling Methods:
The attributes can be accessed like below-
alert(p1._name);

Method calling is similar.
alert(p2.getName());

You can also change the attribute value.
p1._address = "Sariakandi, Bogra";

Note:
  • There is no Encapsulation in JavaScript i.e. any attributes is accessible from anywhere.
  • Interesting (and sometime disgusting) thing is, you can add attributes to an object anytime from anywhere (not necessarily from class). For example- if you want to add another attribute '_gender' with object p1, you can do it like below
    p1._gender = "female";

Add Icon in Website

The icon of a website represents it's identity. Users easily identify/detect website through the icon. A sample is shown below

You can add your icon in your wesite like below:


<head>
<link rel="SHORTCUT ICON" href="http://localhost:8080/images/badhan.ico">
<title>Badhan, A Voluntary Blood Donors' Organization</title>
</head>

 

© 2007 t!ps n tr!cks: November 2008



Template unik dari rohman


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