Javascript继承设计问题

时间:2011-10-20 13:55:27

标签: javascript inheritance

以下代码段显示了我如何创建继承。我受到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();

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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

用作:

inherit(Derived1, Base);

然后在child的构造函数中,你必须调用parent构造函数:

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

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