The task is to implement the extends in es5.
The boilerplate code
const myExtends = (SuperType, SubType) => {
// your code here
}
The function creates a constructor that applies both SuperType and SubType, has the correct prototype chains for instances, and inherits static properties from SuperType.
First, link instance prototype inheritance.
SubType.prototype = Object.create(SuperType.prototype);
SubType.prototype.constructor = SubType;
Create a new constructor that applies both SuperType and SubType
function ExtendedType(...args) {
SuperType.apply(this, args);
SubType.apply(this, args);
}
Make instances use SubType.prototype
ExtendedType.prototype = SubType.prototype;
Implement the static inheritance
Object.setPrototypeOf(ExtendedType, SuperType);
The final code
const myExtends = (SuperType, SubType) => {
// your code here
SubType.prototype = Object.create(SuperType.prototype);
SubType.prototype.constructor = SubType;
function ExtendedType(...args) {
SuperType.apply(this, args);
SubType.apply(this, args);
}
// instance.__proto__ === SubType.prototype
ExtendedType.prototype = SubType.prototype;
// 🔥 Copy SuperType static properties to ExtendedType.prototype
Object.setPrototypeOf(ExtendedType, SuperType);
return ExtendedType;
}
That's all folks!
Top comments (0)