Reputation: 1800
The idea is to implement the calculateSurface method from Shape on the inherited class Rectangle, and calculate the surface with the parameters passed on the Rectangle class.
function Shape (w,h){
this.h = h;
this.w = w;
this.calculateSurface = function (){
return this.w*this.h;
};
}
function Rectangle (w,h){
Shape.apply(this, arguments);
this.w = w;
this.h = h;
this.calcSurface = function(){
return Shape.calculateSurface(this.w, this.h);
};
}
Rectangle.prototype = new Shape();
Rectangle.prototype.constructor = Rectangle;
var rec = new Rectangle(4,4);
console.log(rec.calcSurface());
The error I get is:
Uncaught TypeError: Object function Shape(w,h){
this.h = h;
this.w = w;
this.calculateSurface = function (){
return this.w*this.h;
};
} has no method 'calculateSurface'
Upvotes: 0
Views: 2740
Reputation: 418
Use this instead:
return (new Shape(this.w, this.h)).calculateSurface(this.w, this.h);
Upvotes: 0
Reputation: 9174
Change
return Shape.calculateSurface(this.w, this.h);
to
return this.calculateSurface(this.w, this.h);
Because you are pointing Rectangle
's Prototype to Shape
's in
Rectangle.prototype = new Shape();
Upvotes: 0
Reputation: 490607
This line...
return Shape.calculateSurface(this.w, this.h);
Is looking for a calculateSurface()
method on your Shape()
function. Except it's not there, it's on the object returned by the constructor.
You want something like this...
var self = this;
this.calcSurface = function(){
return self.calculateSurface(this.w, this.h);
};
Also, it may be worth placing calculateSurface()
on Shape
's prototype
property, that way if you create lots of Shape
objects, you only have the method living once in memory.
Upvotes: 2