我有一个简单的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');
}
}
这导致了同样的错误。我该如何解决这个问题?