这是我的 Java Script 对象。
HelloObject(server) {
this.server = server;
this.socketio = require("socket.io");
}
HelloObject.prototype = {
constructor: HelloObject,
listen: function() {
this.serverProcess = this.socketio.listen(this.server);
this.serverProcess.sockets.on('connection', this.connect);
},
connect: function(socket) {
}
}
// I am invoking the object
var socketServer = new HelloObject(server)
// Meaning "this" will refer to sockerServer
socketServer.listen()
很抱歉问了一个愚蠢的问题,我是 javascript 的新手。 我需要将“this”传递给 this.connect 函数。 我试过 this.connect.apply(this) ,结果是我丢失了套接字对象。
最佳答案
在回调中,如果你想让connect
绑定(bind)到当前对象(this
),那么你需要使用Function.prototype.bind
函数,像这样
this.serverProcess.sockets.on('connection', this.connect.bind(this));
关于javascript - 将 this 传递给回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752897/