Coding Challenge Practice - Question 99
Source: Dev.to
Problem Description
Implement an extends helper in ES5 that creates a constructor applying both a super type and a sub type, sets up the correct prototype chain for instances, and inherits static properties from the super type.
Solution
Instance prototype inheritance
SubType.prototype = Object.create(SuperType.prototype);
SubType.prototype.constructor = SubType;
Combined constructor
function ExtendedType(...args) {
SuperType.apply(this, args);
SubType.apply(this, args);
}
Use SubType.prototype for instances
ExtendedType.prototype = SubType.prototype;
Static inheritance
Object.setPrototypeOf(ExtendedType, SuperType);
Final implementation
const myExtends = (SuperType, SubType) => {
// Set up prototype inheritance for instances
SubType.prototype = Object.create(SuperType.prototype);
SubType.prototype.constructor = SubType;
// Constructor that applies both SuperType and SubType
function ExtendedType(...args) {
SuperType.apply(this, args);
SubType.apply(this, args);
}
// Instances should use SubType.prototype
ExtendedType.prototype = SubType.prototype;
// Inherit static properties from SuperType
Object.setPrototypeOf(ExtendedType, SuperType);
return ExtendedType;
};