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


}

0 Comments:

 

© 2007 t!ps n tr!cks: Interface in JavaScript



Template unik dari rohman


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