这两种方法有什么区别?
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this);
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this);
}
// subclass extends superclass
Rectangle.prototype = new Shape();
var rect = new Rectangle();
我看到两个区别:一个很大,一个很小。
小差异在于,在第二种方法中,Rectangle
原型的constructor
属性设置不正确。它指向Shape
,而不是指向Rectangle
。这是JavaScript OO方法中一个非常普遍的错误,大多数时候您都可以避免使用它,因为人们没有太多使用该constructor
属性,但是它就在那里。
最大的不同是Shape()
在第二个构造函数中的附加调用。在您的特定示例中,事情或多或少都可以:Rectangle.prototype
拥有一些您可能不希望拥有的额外属性(x
和y
,两者都为零),但是这些Rectangle
实例将被实例中的相应属性所遮盖反正。同样,这是一种非常常见但很小的错误,经常起作用,足以使您摆脱它。
第二种方法的问题在于,它仅在超类构造函数不需要任何参数时才起作用。您的示例恰好适合该描述,因为它所做的只是将某些属性初始化为默认值。但是,在某些用例中,这种设置并不十分合适,在这种情况下不能使用第二种方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句