extending an ES6 class using ES5 syntax?

/#!/JoePea joe at trusktr.io
Thu Mar 29 02:20:49 UTC 2018


​Rob, you gave an example (I modified barely, to make it work in browser
console):

```js
class FunctionInheritable {
  constructor() {
    return this._constructor.apply(this, arguments);
  }
  _constructor() {}
  static call(context, ...args) {
    return this.apply(context, args);
  }
  static apply(context, args) {
    return this.prototype._constructor.apply(context, args) || context;
  }
}

class YourActualLibraryClass extends FunctionInheritable {
  // all your inheritable classes will have to use `_constructor` instead
of `constructor`
  _constructor(firstArg) {
    // do whatever you want, there are no special requirements on what’s in
here
    this.something = firstArg;
  }
  someLibraryClassFunction() {
    return this.something;
  }
}

// any ES5 or earlier function-style “class” can now inherit with no changes
function SomeEs5FunctionConstructor() {
  this.somethingElse = 'whatever';
  YourActualLibraryClass.call(this, 'something');
}
SomeEs5FunctionConstructor.prototype =
Object.create(YourActualLibraryClass.prototype);​

new SomeEs5FunctionConstructor().someLibraryClassFunction() // "something"
```

It works, but I don't understand why. For example, if I try the following,
it fails:

```js
class Foo {}
Foo.apply(window, ['foo'])
```

Why is it that the static version you implemented above can `.apply` itself
without this same error (and `new` is not being used)?

- Joe


*/#!/*JoePea
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180328/f4666799/attachment.html>


More information about the es-discuss mailing list