0

i'm working on a project and i need to extend

socket.io-client

into a class, for now i can't get it to work, can somebody help ? :D

import io from 'socket.io-client';

export default class Websocket extends io {

  constructor(address) {
    super(address)
  }

  message() {

    alert('1')

  }

}

let socket = new Websocket();

socket.message();

If i try to call message method chrome outputs 'Uncaught TypeError: socket.message is not a function'

Bogdan Crișu
  • 53
  • 1
  • 1
  • 9
  • 1
    If I'm not mistaken, `io` is a function, so you'll have to some fancy-shmancy constructor configuration if you want to continue down the route of extending a class onto it. Take a look at this - http://stackoverflow.com/a/36871498/1599663 – rogMaHall May 01 '17 at 21:34

1 Answers1

3

io is a factory rather than a constructor function and returns an object created by the Manager constructor.

The error message now implies that the constructor function for Websocket returns the object returned by the super call, as distinct from the new object created when calling Websocket as a constructor. This is easily confirmed:

var testObject = {};
function io() { return testObject;}
 
class Websocket extends io {

  constructor(address) {
    super(address)
  }

  message() {

    alert('1')

  }

}

let socket = new Websocket();
console.log( "socket same as testObject: " + (socket === testObject));
console.log( "Websocket.prototype.message: " +  Websocket.prototype.message);

Running the snippet shows Websocket returns the object returned by super, which, since it is not the object created by new, does not inherit methods from Websocket.prototype where the message method is sitting.

This calls for a rethink in design and perhaps further experimentation and learning about how JavaScript object prototyping really works. It also highlights the pitfalls of treating JavaScript as if it were just some yet-another class based language!

traktor
  • 17,588
  • 4
  • 32
  • 53