Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem extending native (es6) classes in Safari

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!

like image 587
LarryFisherman Avatar asked Oct 20 '19 09:10

LarryFisherman


1 Answers

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);
    }
like image 57
georg Avatar answered Nov 15 '22 15:11

georg