0

我想在一些之间建立继承关系。举个例子,Element它是抽象超类Rect,然后Triangle子类

Element除了原型上设置的常用函数外,它的构造函数中有一些通用代码。

Element = function (id, attr) {
    // Setting attributes and id...
    this._callback_click = _bind(this._callback_click, this);
};

我一直在阅读一些问题,例如 this,似乎有不止一种方法可以解决它,尽管它们最终可能是等价的。

  1. 使用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.
    
  2. 使用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;
    
  3. 使用临时构造函数

    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;
    
  4. 使用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)。

4

0 回答 0