Friday, June 19, 2009

Javascript inheritance - the ultimate solution

Stop googling around. This is THE solution for javascript class inheritance unless you are using the Prototype framework

//Simply declare the following methods once:

Object.prototype.Inherits = function( parent )
{
if( arguments.length > 1 )
{
parent.apply( this, Array.prototype.slice.call( arguments, 1 ) );
}
else
{
parent.call( this );
}
}

Function.prototype.Inherits = function( parent )
{
this.prototype = new parent();
this.prototype.constructor = this;
}

//Then declare inheritance easily:

function Mammal( name )
{
this.name_ = name;
}

Cat.Inherits( Mammal );
function Cat( name )
{
this.Inherits( Mammal, name );
}

ColoredCat.Inherits( Cat );
function ColoredCat( name, color )
{
this.Inherits( Cat, name );
}

Lion.Inherits( ColoredCat );
function Lion( name )
{
this.Inherits( ColoredCat, name, "gold" );
}

Source code obtained from: http://www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html

1 comment:

Anonymous said...

[url=http://vtyupdr.com]CWwND[/url] , uSpkloVq , http://pyfnknfrtw.com