How I learned from a crazy idea / Subclassing an ES6 class in an 'old' class

by Arnaud Buchholz

HTML

<script src="https://arnaudbuchholz.github.io/blog/jsfiddle-assert.js"></script>

JavaScript

class A {
  constructor () {
    this._a = "A"
  }
}

class B extends A {
  constructor (param) {
    super()
    this._b = "B"
    this._param = param
  }
}

// This is the constructor that would be provided in the gpf.define dictionary
function constructorOfC (param2) {
  this.$super("test")
  this._c = "C"
  this._param2 = param2
}

// We need a way to create a class C that inherits from B calling constructorOfC
function C () {
  var
    newC,
    $super = function () {
      newC = Reflect.construct(B, arguments, C);
    },
    proxy = new Proxy({}, {
      get: function (obj, property) {
        if (property === '$super') {
          return $super;
        }
        return newC[property];
      },
      set: function (obj, property, value) {
        newC[property] = value;
        return true;
      }
    });
  constructorOfC.apply(proxy, arguments);
  return newC;
}
C.prototype = Object.create(B.prototype);

// Validation
var c = new C("test2");
assert(() => c instanceof A);
assert(() => c._a === "A");
assert(() => c instanceof B);
assert(() => c._b === "B");
assert(() => c._param === "test");
assert(() => c instanceof C);
assert(() => c._c === "C");
assert(() => c._param2 === "test2");