I'd like to establish an inheritance relation between some classes. Take, for instance, Element
which would be the abstract superclass, and then Rect
and Triangle
as child classes.
Element
has some common code in its constructor, besides the common functions set on its prototype.
Element = function (id, attr) {
// Setting attributes and id...
this._callback_click = _bind(this._callback_click, this);
};
I've been reading some questions, such as this, and it seems there's more than one way to go about it, although they might be equivalent in the end.
Using
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.
Using
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;
Using temporary constructors:
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;
Using
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;
Does any of these methods have an (dis)advantage over the others?
I suspect the clone
method might not be correct, although I'm not sure as to what the reason could be.
Finally, correct me if I'm wrong, but I believe the new
method could show unexpected results, since _callback_click
is bound twice (when setting the prototype, and when calling the Element
constructor from within Rect
).