簡體   English   中英

未捕獲的TypeError:對象函數沒有方法

[英]Uncaught TypeError: Object function has no method

我們的想法是在繼承的類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' 

這條線......

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

正在尋找Shape()函數的calculateSurface()方法。 除非它不在那里,它在構造函數返回的對象上。

你想要這樣的東西......

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

jsFiddle

此外,可能值得在Shapeprototype屬性上放置calculateSurface() ,這樣如果你創建了很多Shape對象,你只需要在內存中存活一次。

請改用:

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

更改

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

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

因為你將Rectangle的Prototype指向Shape的in

Rectangle.prototype = new Shape();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM