我想在一些类之间建立继承关系。举个例子,Element
它是抽象超类Rect
,然后Triangle
是子类。
Element
除了原型上设置的常用函数外,它的构造函数中有一些通用代码。
Element = function (id, attr) {
// Setting attributes and id...
this._callback_click = _bind(this._callback_click, this);
};
我一直在阅读一些问题,例如 this,似乎有不止一种方法可以解决它,尽管它们最终可能是等价的。
使用
new
:Rect = function (id, attr) { Element.call(this, id, attr); // Setting Rect's own attributes... }; Rect.prototype = new Element(null, {}); Rect.prototype.constructor = Rect; // Seems somewhat pointless to pass these arguments, but I have none // at this point in the code.
使用
Object.create
:Rect = function (id, attr) { Element.call(this, id, attr); // Setting Rect's own attributes... }; Rect.prototype = Object.create(Element.prototype); Rect.prototype.constructor = Rect;
使用临时构造函数:
function makePrototype(superclass) { function f() { } f.prototype = superclass.prototype; f.prototype.constructor = f; return new f(); } Rect = function (id, attr) { Element.call(this, id, attr); // Setting Rect's own attributes... }; Rect.prototype = makePrototype(Element); Rect.prototype.constructor = Rect;
使用
clone
:function clone(object) { var key, copy = {}; for (key in object) { copy[key] = object[key]; } return copy; } Rect = function (id, attr) { Element.call(this, id, attr); // Setting Rect's own attributes... }; Rect.prototype = clone(Element.prototype); Rect.prototype.constructor = Rect;
这些方法中的任何一种是否比其他方法具有(不利)优势?
我怀疑该clone
方法可能不正确,尽管我不确定原因可能是什么。
最后,如果我错了,请纠正我,但我相信该new
方法可能会显示意外结果,因为_callback_click
绑定了两次(设置原型时,以及Element
从内部调用构造函数时Rect
)。