javascript - 如何将 JavaScript 回调设置为外部(包装)对象的方法?

标签 javascript function class methods scope

如何将 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/

相关文章:

javascript - 从其他子域页面访问子域 iframe url

javascript - 在 React(客户端)中上传 .json 文件并将其发送到 Node(服务器端)

python - 在 python 中不满足条件时不创建对象?

使用将在派生构造函数中构造的参数调用的 C++ 基本构造函数

php - while 循环在第一行后停止

php - 如何实现多人浏览器游戏?

javascript - mxGraph:移动边的句柄点时会触发哪个事件?

javascript使函数内的变量成为全局变量

c++ - 重载预增量运算符时是否必须返回对对象的引用?

c++ - typedef 函数不是类型名?