【发布时间】:2011-11-27 19:45:38
【问题描述】:
我正在尝试学习如何在 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() { ... }在这种情况下不起作用吗? -
原型是正确的方法。它将创建一次 toString 函数。在构造函数中,它会随着每个新的创建。
-
John Resig 对类继承有一些非常深刻的看法,还有一个很棒的小脚本可以解决 js 中的许多继承问题:ejohn.org/blog/simple-javascript-inheritance
-
以这种方式扩展需要注意的一点:
new Shape().constructor === Shape,但new Circle().constructor !== Circle。
标签: javascript jquery inheritance