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 recta开发者_开发知识库ngle = new myRectangle(0, 5, 5);
alert(rectangle.returnArea());
The problem is that
this.returnArea = function(){
return 'wrong override';
}
will set the property of that particular instance (as you are correctly calling the parent's constructor on the new MyRectangle
instance) , and this will "override" all inherited methods.
Your prototype chain looks like this:
+------------------+ +------------------+ +------------------+
| MyRectangle | | MyRectangle | | MyGeometry |
| instance |------->| prototype |------->| prototype |
| | | | | |
| wrong returnArea | | right returnArea | | |
+------------------+ +------------------+ +------------------+
(MyGeometry instance)
where the retunArea
method at the instance is the one you assign in the MyGeometryObject
constructor and the one of the prototype is the one you have overwritten.
But if you assign this method to MyGeometryObject
's prototype
function MyGeometryObject(r, x, y) {
this.r = r;
this.x = x;
this.y = y;
}
MyGeometryObject.prototype.returnArea = function(){
return 'wrong override';
}
then it will work, as the right returnArea
method will come earlier in the prototype chain:
+------------------+ +------------------+ +------------------+
| MyRectangle | | MyRectangle | | MyGeometry |
| instance |------->| prototype |------->| prototype |
| | | | | |
| | | right returnArea | | wrong returnArea |
+------------------+ +------------------+ +------------------+
(MyGeometry instance)
Further notes:
- Constructor function names should start with a capital letter.
If you set the prototype of
MyRectangle
this way, you should also set theconstructor
property back toMyRectangle
:MyRectangle.prototype = new MyGeometryObject(); MyRectangle.prototype.constructor = MyRectangle;
精彩评论