0

思路是在继承的类Rectangle上实现Shape中的calculateSurface方法,用Rectangle类上传递的参数计算曲面。

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());

我得到的错误是:

    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' 
4

3 回答 3

2

这条线...

return Shape.calculateSurface(this.w, this.h);

正在为您的功能寻找一种calculateSurface()方法。Shape()除了它不存在,它在构造函数返回的对象上。

你想要这样的东西...

var self = this;
this.calcSurface = function(){
    return self.calculateSurface(this.w, this.h);
};

js小提琴

此外,可能值得将其calculateSurface()放在Shape'sprototype属性上,这样如果您创建大量Shape对象,则该方法只会在内存中存在一次。

于 2012-10-29T11:53:52.247 回答
0

改用这个:

return (new Shape(this.w, this.h)).calculateSurface(this.w, this.h);
于 2012-10-29T11:56:16.963 回答
0

改变

return Shape.calculateSurface(this.w, this.h);

return this.calculateSurface(this.w, this.h);

因为您将Rectangle's Prototype指向Shape's in

Rectangle.prototype = new Shape();

于 2012-10-29T11:59:32.997 回答