[英]Uncaught TypeError: Object function has no method
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. 我们的想法是在继承的类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());
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'
This line... 这条线......
return Shape.calculateSurface(this.w, this.h);
Is looking for a calculateSurface()
method on your Shape()
function. 正在寻找
Shape()
函数的calculateSurface()
方法。 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. 此外,可能值得在
Shape
的prototype
属性上放置calculateSurface()
,这样如果你创建了很多Shape
对象,你只需要在内存中存活一次。
请改用:
return (new Shape(this.w, this.h)).calculateSurface(this.w, this.h);
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指向Shape
的in
Rectangle.prototype = new Shape();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.