JavaScript: Extending Singletons experiment with ES6

Radu B. Gaspar
2 min readAug 12, 2016

--

I’ll be honest with you… I don’t know if this is a feature or a bug, but it feels like a bug.

While preparing materials for another article I ran into this gold nugget. Let me describe the scenario / setup before I show you the code:

  1. I have a class called EventDispatcher which is a Singleton
  2. Another class called Keyboard extends EventDispatcher
  3. A third class called PlayerController extends Keyboard
  4. The final class is PlayerModel and it also extends EventDispatcher

Here’s a visual representation of the description above:

The class methods and logic have been removed for presentational purposes; here’s the code:

To my awe, playerCtrl is actually an instance of playerModel. This was tested in Chrome, Firefox, IE, Babel repl, NodeJS and in ES6Fiddle. The result is consistent throughout the browsers, but the instance is returned correctly in ES6Fiddle (for some reason) and incorrectly in the rest (try it yourself). There are two ways of “fixing” this issue:

  1. By making sure PlayerModel doesn’t extend EventDispatcher or
  2. By making sure EventDispatcher is not a Singleton

Since the EventDispatcher constructor can be accessed and it returns a valid instance (regardless if that instance is new or not), I wonder why this fails miserably. What’s your take on this?

P.S.

  • Any instance after PlayerModel will be PlayerModel
  • Swapping lines 35 and 36 will produce instances of PlayerController for both playerCtrl and playerModel.

--

--