如何将 websocket
属性 onopen
回调委托(delegate)给外部对象的方法 with outer-object as this
, not websocket as 这个
? (因为 websocket 没有函数 showAlert
换句话说:如何在 webscoket connect 上调用我的 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); };
最佳答案
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);
}
关于javascript - 如何将 JavaScript 回调设置为外部(包装)对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22452029/