0

I have a simple JS class which looks like this:

function Connection(){
  this.conn = new WebSocket("ws://my.website:9090");
  this.connection.onmessage = function(message){
    var data = JSON.parse(message.data);

    switch (data.type) {
      case "login":
        this.onLogin(data.success);
        break;
      // removed other cases for brevity
      default:
        console.log("Data from server was not as expected" + JSON.stringify(data));
    }
  }
}

Then, I added an onLogin method using prototype:

Connection.prototype.onLogin = function(success) {
  console.log("login, success is " + success);
  $("#loginModal").modal('hide');
}

When I created a connection and the server returned login, it said TypeError: this.onLogin is not a function. I tried putting this prototype method before and after the Connection class, but that didn't do anything. So, then I tried to move the onLogin function into the Conection function:

function Connection(){
  //same stuff as at top of question
  this.onLogin = function(success) {
    console.log("login, success is " + success);
    $("#loginModal").modal('hide');
  }
}

This resulted in the same error. How do I fix this?

user2367593
  • 171
  • 1
  • 4
  • 16

0 Answers0