How I learned from a crazy idea

The idea

Building JavaScript classes

The ‘old’ way

The ES6 way

Subclassing an ‘old’ class in an ES6 class

Subclassing an ES6 class in an ‘old’ class

Class constructor cannot be invoked without ‘new’

Reproduce the behavior in the ‘old’ way

Notable differences between the two ways of creating class

Detecting an ES6 class constructor

Subclassing an ES6 class in an ‘old’ class

ConstructorOfB

  • gpf.define is used with a dictionary having the $extend property set to an ES6 class constructor
  • a constructor property points to a JavaScript function
  • this.$super is called to invoke the base constructor
  • to respect the ES6 constraints, this.$super must be called before any use of this or the construction should fail

Attempt number 1: The copycat

  • the constructor is a copy of constructorOfC with this.$super being replaced with super
  • the base class will be passed as a parameter

Attempt number 2: Applying constructorOfC on this

Attempt number 3: Building this

Attempt number 4: An unusual way to invoke a constructor

  • Reflect.construct builds an instance of C initialized with constructor of B
  • The initial value of this is ignored, a wrapper is used to invoke constructorOfC
  • The final instance is returned at the end of the class constructor

Attempt number 5: Shadowing the object

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store