JavaScript类继承

3

我正在尝试学习如何在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() { ... } 在这种情况下不起作用吗? - Connell
不是的。看看它们之间的区别: http://jsfiddle.net/paptamas/qDSkj/ 和 http://jsfiddle.net/paptamas/cbnLB/ - Tamás Pap
1
原型是正确的方式。它将创建一次toString函数。在构造函数中,它会随每个新对象的创建而创建。 - Joe
3
John Resig对类继承有一些深刻的见解,还提供了一个非常好的小脚本,能够解决JavaScript中许多继承问题:http://ejohn.org/blog/simple-javascript-inheritance/ - Kato
需要注意的一点是:通过这种方式进行扩展,new Shape().constructor === Shape,但是 new Circle().constructor !== Circle - pimvdb
1个回答

0

根据我的理解:

  1. 当你将.toString()移入构造函数时,.toString()就成为了实例的一个显式成员。因此,任何对.toString()的调用都会触发该显式成员。

例如:http://jsfiddle.net/paptamas/qDSkj/

  1. 但是,当你将其定义为原型时(在没有名为.toString()的显式成员的情况下),任何对.toString()方法的调用都会触发为调用对象类型(在你的情况下是Circle)定义的.toString()函数。

例如:http://jsfiddle.net/paptamas/cbnLB/

换句话说,显式成员优先于原型定义,当你说

this.toString = function() ...

你正在将该函数定义为实例成员(而不是类型成员 - 这在某种程度上也不是最优化的)。

敬礼。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接