简体   繁体   中英

Javascript inheritance design issue

The following snippet shows how I created my inheritance. I got inspired by this article.

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);
}

When this js file is loaded by the browser all the contructors will be called.

Derived2.prototype = new Derived1();

This can lead to some unexpected behaviour.

Is there any way to stop this behaviour ?

Imo this is a bad inheritance pattern. What if the parent constructor function expects parameters to be passed?

The prototype of the child class should inherit from the prototype of the parent class, not an instance of it. Several libraries implement this way:

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

Used as:

inherit(Derived1, Base);

Then in the child's constructor function, you have to call the parents constructor function:

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

Of course you can also add a superclass property if you wanted to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM