I'm having trouble extending the native WebSocket
class using es6 classes.
The following piece of code works on Chrome and Firefox, but not on Safari:
class MyWebSocket extends WebSocket {
doSomething() {
console.log('hi');
}
}
let ws = new MyWebSocket('wss://127.0.0.1:4000');
ws.doSomething();
TypeError: ws.doSomething is not a function. (In 'ws.doSomething()', 'ws.doSomething' is undefined)
console.log('MyWebSocket.prototype')
lets me see that the function was added to the prototype.
This happens with a few other builtin classes, Animation
being one, but not with others, like Date
for example.
Has anyone run into this? Is this a bug in Safari? Any advice is appreciated!
Yes, looks like a bug. The WebSocket
constructor is probably hardcoded to return a WebSocket
instance. It doesn't respect Symbol.species
either.
As a workaround you could use something like this:
class MyWebSocket extends WebSocket {
constructor(url) {
super(url);
Object.setPrototypeOf(this, MyWebSocket.prototype);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With