How to override constructor of prototype/intercept object creation in JavaScript?

How to override constructor of prototype/intercept object creation in JavaScript?

I would like to intercept all instance creations of EventSource. I tried the following code:

EventSource.prototype.constructor = function(url, config) {
    EventSource(url, config);
    console.log("intercepted");
}

to override the constructor. It does not work. But the following does work:

EventSource.prototype.sayHi = () => alert("Hi");
new EventSource("my-data").sayHi()

How can I achieve something similar for the constructor/in general instance creation?

I tried searching on the internet and the above code.

Answer

You could override the class itself:

class MyEventSource extends EventSource{
  constructor(...args){
    super(...args);
    console.log('EventSource created');
  }
}

window.EventSource = MyEventSource;

new EventSource("my-data")

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions