[英]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 。
此外,可能值得在Shape
的prototype
屬性上放置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.