Why does the Event interface have a constructor in Javascript and how to implement DOM based custom events?

66 Views Asked by At

I'm relatively new to JavaScript and while trying to implement a custom event for DOM manipulation, I came across the Event interface in the MDN Web Docs. What caught my attention is that it's defined as an interface, but it also seems to have a constructor (new Event(...)). From my understanding, interfaces in other programming languages don't typically have constructors, so this concept is a bit confusing for me.

Could someone please clarify how an interface in JavaScript, like the Event interface, can have a constructor? What's the purpose of having a constructor in an interface, and how should I approach utilizing it when working with custom events?

My confusion stems from the fact that the Event is labelled as an interface, yet it appears to have a constructor (new Event(...)), which seems more akin to a class. My understanding of interfaces from other programming languages leads me to think that they primarily define method signatures, without constructors.

Here's what I'd like to do: design a custom event using best practices. Should I extend or implement the Event interface, or is that even the right approach? Could someone clarify whether the Event interface is closer to a class or an interface in the traditional sense? Additionally, I'd appreciate any guidance or examples on how to proceed with creating a custom event while adhering to JavaScript conventions.

1

There are 1 best solutions below

0
Bergi On

MDN uses the term "interface" in the abstract, like IDL does:

Objects are entities that have identity and which are encapsulations of state and behavior. An interface is a definition that declares some state and behavior that an object implementing that interface will expose.

That's the kind of interface that Event is - you could also call it a type declaration. And in fact, Web IDL does only use such interfaces to define all its programming interfaces, which are then mapped to concrete code in different programming languages. The Event might be implemented as an interface, a class, a type, an abstract class, a module, or something else, depending on the programming language. In JavaScript in particular, there are no "interfaces", so Event becomes a global function object with a .prototype property - according to the WebIDL ECMAScript binding.

Also, Event was not always constructible. Back in DOM level 2, there was no constructor, you instead had to create events via document.createEvent(…).initEvent(…) which was rather ugly.