1

I want to inherit EventTarget object.

So I tried the following code, which causes an error "Illegal constructor".

class OwnClass extends EventTarget {
  constructor () {
    super();
  }
}
function eventHandler () {
  console.log( arguments );
}
let et = new OwnClass();
et.addEventListener( "Own Event", eventHandler );
et.dispatchEvent( new Event( "Own Event" ) );

So I use following code, currently.

class OwnClass extends Document {
  constructor () {
    super();
  }
}
function eventHandler () {
  console.log( arguments );
}
let et = new OwnClass();
et.addEventListener( "Own Event", eventHandler );
et.dispatchEvent( new Event( "Own Event" ) );

But this cause meaningless memory usage.

Is there a way to inherit EventTarget directly?

Isitea
  • 741
  • 5
  • 13
  • Your code examples don't seem right: Both of them throw a `SyntaxError`, because you're calling `super()` in the class body rather than in the constructor or another function. – Tulir Jan 21 '18 at 08:51
  • I miss wrapping with the constructor. – Isitea Jan 21 '18 at 09:24
  • 1
    That's pretty much useless. If you just omit the constructor, it will automatically fall back to the parent constructor. Anyway, maybe you could [implement your own EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget#Example)? – Tulir Jan 21 '18 at 10:02
  • Thank you for your answer, but I had seen that already. Is there no way to implement EventTarget without that MDN way? – Isitea Jan 23 '18 at 07:56
  • No. [Full answer in this other SO question](https://stackoverflow.com/a/22732701/1809564). – joaoguerravieira Feb 03 '18 at 18:36
  • Possible duplicate of [Illegal Invocation on addEventListener](https://stackoverflow.com/questions/22697502/illegal-invocation-on-addeventlistener) – joaoguerravieira Feb 03 '18 at 18:38

1 Answers1

2

Maybe it comes a bit late for answering but now you can use the EventTarget class

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/EventTarget

asdru
  • 1,147
  • 10
  • 19