AI solution for JavaScript Coding Question on BFE.dev
53. write your own `extends` in es5
Here's one possible solution using ES5 syntax:
function myExtends(SuperType, SubType) { function F() {} // create a temporary constructor function F.prototype = SuperType.prototype; // set the prototype of F to be the same as SuperType's prototype SubType.prototype = new F(); // create a new prototype object for SubType that inherits from F's prototype SubType.prototype.constructor = SubType; // reset the constructor property of SubType's prototype return SubType; // return the new subtype constructor}
Explanation:
-
First, we create a new constructor function
F
that doesn't do anything, just for the purpose of temporarily storing a copy ofSuperType
's prototype. -
We then set the prototype of
F
to be the same asSuperType
's prototype, so thatF
now inherits fromSuperType
. -
Next, we create a new prototype object for
SubType
by instantiatingF
. This means thatSubType
now inherits fromF
and therefore fromSuperType
. -
Finally, we reset the
constructor
property ofSubType
's prototype to point back toSubType
. -
We return
SubType
, which now has a prototype chain that includes bothF
andSuperType
.
With this new myExtends
function, we can create subtypes that inherit from super types:
const InheritedSubType = myExtends(SuperType, SubType);console.log(new InheritedSubType('example')); // SubType { name: 'example', forSub: [ 3, 4 ], from: 'sub' }console.log(InheritedSubType.staticSuper); // staticSuperconsole.log(InheritedSubType.staticSub); // staticSubconsole.log(typeof InheritedSubType.superMethod); // functionconsole.log(typeof InheritedSubType.subMethod); // function
The InheritedSubType
constructor now inherits both from SuperType
and SubType
and has access to all their properties and methods.