DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 99

The task is to implement the extends in es5.

The boilerplate code

const myExtends = (SuperType, SubType) => {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Create a new constructor that applies both SuperType and SubType

function ExtendedType(...args) {
  SuperType.apply(this, args);
  SubType.apply(this, args);
}
Enter fullscreen mode Exit fullscreen mode

Make instances use SubType.prototype

ExtendedType.prototype = SubType.prototype;
Enter fullscreen mode Exit fullscreen mode

Implement the static inheritance

Object.setPrototypeOf(ExtendedType, SuperType);
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)