【问题标题】:Javascript inheritance design issueJavascript继承设计问题
【发布时间】:2011-10-20 13:55:26
【问题描述】:

以下 sn-p 显示了我是如何创建继承的。我受到this 文章的启发。

function Base() {
    this.init();
}

Base.prototype.init = function () {
};

Derived1.prototype = new Base();
Derived1.prototype.constructor = Derived1;
Derived1.superclass = Base.prototype;

function Derived1() {    
}

Derived1.prototype.init = function() {
    Derived1.superclass.init.call(this);
};

Derived2.prototype = new Derived1();
Derived2.prototype.constructor = Derived2;
Derived2.superclass = Derived1.prototype;

function Derived2() {
    Derived2.superclass.init.call(this);
}

当浏览器加载这个js文件时,所有的构造函数都会被调用。

Derived2.prototype = new Derived1();

这可能会导致一些意想不到的行为。

有没有办法阻止这种行为?

【问题讨论】:

  • 您能否更具体地说明意外行为?
  • 例如,如果您在构造函数中进行一些 DOM 操作。

标签: javascript inheritance


【解决方案1】:

Imo 这是一个糟糕的继承模式。如果父构造函数期望传递参数怎么办?

子类的原型应该继承自父类的原型,而不是它的实例。有几个库以这种方式实现:

function inherit(Child, Parent) {
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}

用作:

inherit(Derived1, Base);

那么在孩子的构造函数中,你要调用父母的构造函数:

function Child() {
    Parent.call(this);
}

当然,如果您愿意,您也可以添加 superclass 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多