3

I have an object that is as follows:

{ except: player => ({ send :player.getSocket().broadcast.emit }) }

However this means that the this in the emit function is not the one it expects it to be (the broadcast object).

So I can do:

{ except: player => ({ send : (msg, data) => player.getSocket().broadcast.emit(msg, data) }) }

But this is ugly, especially if the arguments change. So the alternative is:

{ except: player => ({ send : (t = player.getSocket().broadcast).emit.bind(t) }) }

But is there a tidier way of doing this, of assigning a function to an object while maintaining it's this as it's parent object.

Jonathan.
  • 51,850
  • 46
  • 174
  • 275

2 Answers2

0

You can specify who this will be by calling the function with apply or call. The first parameter to these methods will be this within the body of the function.

Cristian Vrabie
  • 3,770
  • 5
  • 26
  • 46
  • I don't want to actually call the function here though. – Jonathan. May 27 '15 at 14:16
  • True, so your `.bind ` syntax seems the most appropriate. The problem is that you need to create a closure in order to capture the thing that you consider the parent. I don't think there's a way around that as [`this` is very weird in JS](http://stackoverflow.com/a/3127440/292921). – Cristian Vrabie May 27 '15 at 14:22
0

Using bind in order to maintain the scope of this is actually a good solution to your problem, the way I see it, it makes the code a lot more understandable because you can know to what object the function actually belongs, by using apply or call, when you read the code you wont know to what this the function/method belongs. As far as i know, bind is a pretty good solution to your problem here.

taxicala
  • 20,376
  • 7
  • 31
  • 65