I’m new to OOP in javascript. I can’t get it right when I want to override a method. I made an example of my problem below. Also in http://jsfiddle.net/sRyQA/
function myGeometryObject(r, x, y){
this.r = r;
this.x = x;
this.y = y;
var OBJ = this;
this.returnArea = function(){
return 'wrong override';
}
}
function myRectangle(r, x, y){
myGeometryObject.call(this, r, x, y);
}
myRectangle.prototype = new myGeometryObject();
myRectangle.prototype.returnArea = function(){
return 'right override';//I want JS to use this method
}
var rectangle = new myRectangle(0, 5, 5);
alert(rectangle.returnArea());
The problem is that
will set the property of that particular instance (as you are correctly calling the parent’s constructor on the new
MyRectangleinstance) , and this will “override” all inherited methods.Your prototype chain looks like this:
where the
retunAreamethod at the instance is the one you assign in theMyGeometryObjectconstructor and the one of the prototype is the one you have overwritten.But if you assign this method to
MyGeometryObject‘sprototypethen it will work, as the right
returnAreamethod will come earlier in the prototype chain:Further notes:
If you set the prototype of
MyRectanglethis way, you should also set theconstructorproperty back toMyRectangle: