Skip to content
Advertisement

Why EventTarget subclass instances lose their names?

The current version of JavaScript implements EventTarget as a class instead of an interface, so you can create an instance of EventTarget with all the expected methods.

I tried to copy/paste the EventTarget example in the console (on both Chrome and Firefox) but when I inspect the myEventTarget object (that is build as a subclass of EventTarget named MyEventTarget), the console says that myEventTarget is an EventTarget, not a MyEventTarget.

This is the code

JavaScript

Why the console says that myEventTarget is just an EventTarget?

I found this thing quite uncommon because if I type the following code the console says that myEventTarget is actually a MyEventTarget instance

JavaScript

so if I use EventTarget as superclass, the instances lose their constructor name? I understand that is not a big deal, I think that print class names is just for debugging purpose but there is a reason for this?

Advertisement

Answer

This happens because EventTarget overrides Symbol.toStringTag and you inherit this behaviour. You can override it to be whatever you want.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement