传递给callback函数?

这是我的Java脚本对象。

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),结果发生了什么是我失去了套接字对象。

在callback中,如果你想把connect绑定到当前对象( this ),那么你需要使用Function.prototype.bind函数,就像这样

 this.serverProcess.sockets.on('connection', this.connect.bind(this)); 

你可以使用JavaScriptclosures:

 var $this = this; this.serverProcess.sockets.on('connection',function () { $this.connect(); });