我正在尝试学习如何在JavaScript中使用“类”。
这是我的代码:
function Shape(x, y) {
this.x= x;
this.y= y;
}
Shape.prototype.toString= function() {
return 'Shape at '+this.x+', '+this.y;
};
function Circle(x, y, r) {
Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
this.r= r;
}
Circle.prototype= $.extend(true, {}, Shape.prototype);
Circle.prototype.toString= function() {
return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}
var c = new Circle(1,2,3);
alert(c);
在Shape的构造函数内定义toString函数是否可行,或者在这种情况下没有意义?
this.toString = function() { ... }
在这种情况下不起作用吗? - Connellnew Shape().constructor === Shape
,但是new Circle().constructor !== Circle
。 - pimvdb