Skip to content Skip to sidebar Skip to footer

Extending Es2015 Through Prototype Inheritance

I am making a library where I would like to provide a helper to extend the base class so that users can extend it even if they are not using ES2015 themselves. The issue is that if

Solution 1:

ES6 created a clearer distinction between [[Call]] and [[Construct]] operations. ES6 classes can only be constructed using a [[Construct]] operation, but .call/.apply are [[Call]] operations. To use [[Construct]], you'll need to use Reflect.construct() to create the new instance. e.g.

constructor = function () {
  returnReflect.construct(Object.getPrototypeOf(constructor), arguments);
};

or

constructor = function () {
  returnReflect.construct(currentClass, arguments);
};

I'll also note however that this also ignores another feature new in ES6, which is new.target. You'll also want to preserve that, by doing

constructor = function () {
  returnReflect.construct(currentClass, arguments, new.target);
};

to ensure that the things behave the same way as class syntax would.

Also note that you must not use this inside this function. It is the return value of Reflect.construct that is the new instance, so if you wanted to work with it in your own custom constructor, you'll want to do

constructor = function () {
  const _this = Reflect.construct(currentClass, arguments, new.target);

  _this.foo = "foo";
  return _this;
};

however, if you think about it, this is essentially all the same as doing

constructor = class extends currentClass {}

Post a Comment for "Extending Es2015 Through Prototype Inheritance"