Multiple Inheritance

Do you ever wish for multiple inheritance? That is, being able to inherit the methods and properties from multiple classes? For example, let’s say you have:

class ClassA {
	public varA;
	public functionA {
		return varA
	}
}

class ClassB {
	public varB;
	public functionB {
		return varB
	}
}

And you want

class ClassC {
	public varA;
	public varB;

	public functionA {
		return varA;
	}

	public functionB {
		return varB
	}
}

But you don’t want to have to spell it out because there’s a lot more in functions functionA and functionB than I’ve put here.

Conventional wisdom says that interfaces are a way to get around the desire for multiple inheritance, but that’s not true because interfaces only provide the signature for the methods, not the implementation.

Well, JavaScript is a stunningly versatile language. You can mimic multiple inheritance by creating a method to copy the functions from A and B to C. I’ve prototyped the method (and I thumb my nose at people who say this is bad practice – that’s how the language was designed). It looks like this:

Object.prototype.inherit = function (ancestor) {
	for (let property in ancestor ["prototype"]) {
		this [property] = ancestor ["prototype"][property];
	}// for;
}// inherit;

It can be invoked in your class constructor, thusly:

class ClassC {
	constructor () {
		this.inherit (ClassA);
		this.inherit (ClassB);
	}
}

It’s not exactly multiple inheritance, but it comes close.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *