2014-03-31 145 views
1

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

+0

闭包或绑定都可以工作。在某些情况下(但不是你的),当使用附加到所有函数的'Function.apply(thisObject,argumentsArray)'调用函数时,可以设置'this'。 – Paul

回答

2

在回调,如果你想connect绑定到当前对象(this),那么你需要使用Function.prototype.bind功能,这样

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

假设我有另一个我想传递的参数,以及“this”,我将如何实现这一点? –

+0

@MikeChung你的意思是,你想传递另一个参数到'connect'?你可以简单地做'this.connect.bind(this,parameter)'。当'connect'被调用时,'parameter'将成为它的第一个参数。 – thefourtheye

+0

谢谢!那很完美! = d –

1

您可以使用JavaScript关闭了这一点:

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