Monday, September 5, 2011

Javascript Object Inheritance and Overwriting - Using Constructors

Read the comments(green text) in the code below
function shape(){ 
this.name='shape';
this.tostring = function() {return this.name;};
}

function TwoDshape(){
this.name = '2D shape';
}

function Triangle(side,height){
this.name = 'Triangle';
this.side = side;
this.height = height;
this.getArea = function(){return this.side * this.height /2;};
}

//Inheritance
//overwriting objects sort of. if you print the TwoDshape.constructor it will show the assigned object but all the properties from inside both functions are accessible unless one has the same name, the original is printed so below shape() properties is added to TwoDshape() and TwoDshape() is added to Triagle(). making Triangle() have itself and shape() and TwoDshape() propeties within

TwoDshape.prototype = new shape();
Triangle.prototype = new TwoDshape();



//good idea to reset the constructor after inheriting, because overwrite the object has negative side effects
TwoDshape.prototype.constructor = TwoDshape;
Triangle.prototype.constructor = Triangle; http://www.blogger.com/img/blank.gif

var my = new Triangle(5,10);
document.write(my.getArea());
document.write(my.tostring());

The output is 25Triangle

Another example of javascript inheritance using the pure object

Special Thanks Object-Oriented Javascript

No comments:

Post a Comment