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.
MDN uses the term "interface" in the abstract, like IDL does:
That's the kind of interface that
Eventis - you could also call it a type declaration. And in fact, Web IDL does only use suchinterfaces to define all its programming interfaces, which are then mapped to concrete code in different programming languages. TheEventmight 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", soEventbecomes a global function object with a.prototypeproperty - according to the WebIDL ECMAScript binding.Also,
Eventwas not always constructible. Back in DOM level 2, there was noconstructor, you instead had to create events viadocument.createEvent(…).initEvent(…)which was rather ugly.