Thursday, November 6, 2008

Inheritance using Closures and Prototypes

example for Closure:

function Car(name)
{
this.Name = name;
this.Drive = Drive;
}
function Drive(){}

function SuperCar(name)
{
//implement closure inheritance
this.inheritsFrom = Car;
this.inheritsFrom(name);
//add new method
this.Fly = Fly;
}
function Fly(){}

example for Prototyping:

function Car(name)
{
this.Name = name;
}
Car.prototype.Drive = function()
{
document.write("My Name is " + this.Name + " and I am driving
");
}
SuperCar.prototype = new Car();
SuperCar.prototype.constructor = SuperCar();
SuperCar.prototype.Fly = function()
{
document.write("My Name is " + this.Name + " and I am flying
");
}
function SuperCar(name)
{
Car.call(this,name);
}

No comments: