如何将websocket
属性onopen
回调委托给外部对象的方法,外部对象为this
,而不是websocket为this
? (beaceuse websocket没有函数showAlert
换句话说:如何在webscoket上呼叫我的MyClient.showConnected
?
function MyClient() {
this.websocket = {};
}
MyClient.prototype.showAlert = function( ) {
alert("Connected!");
};
MyClient.prototype.showConnected = function( evt ) {
this.showAlert();
};
MyClient.prototype.connect = function( url ) {
this.websocket = new WebSocket(url);
this.websocket.onopen = this.showConnected;
}
这种方式产生this.showAlert is not a function
。用法:
var client = new MyClient();
client.connect("ws://.......");
这也是不工作:
this.websocket.onopen = function(evt) { this.onOpen(evt); };
答案 0 :(得分:2)
function MyClient() {
this.websocket = {};
}
MyClient.prototype.showAlert = function( ) {
alert("Connected!");
};
MyClient.prototype.connect = function( url ) {
this.websocket = new WebSocket(url);
this.websocket.onopen = this.showAlert.bind(this);
}
答案 1 :(得分:0)
这是你想要的吗?
function MyClient() {
this.websocket = {};
}
MyClient.prototype.showAlert = function( ) {
alert("Connected!");
};
MyClient.prototype.connect = function( url ) {
this.websocket = new WebSocket(url);
var that = this;
// that is hidden in connect namespace, some people use _this instead
this.websocket.onopen = function( evt ) {
that.showAlert();
};
}
我认为您的问题是onopen
是事件。如果是事件,JS总是更改this
。然后,最好的选择是使用某个命名空间中的变量并在其中保存this
。