无法找到类方法

时间:2017-08-07 20:07:01

标签: javascript javascript-objects

我有一个简单的JS类,如下所示:

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));
    }
  }
}

然后,我使用onLogin添加了prototype方法:

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

当我创建连接并且服务器返回login时,它说TypeError: this.onLogin is not a function。我尝试在prototype类之前和之后放置此Connection方法,但这没有做任何事情。那么,我尝试将onLogin函数移动到Conection函数:

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

这导致了同样的错误。我该如何解决这个问题?

0 个答案:

没有答案