Link to original in JavaScript
I have an object that looks like this:
{ except: player => ({ send :player.getSocket().broadcast.emit }) }
However, this means that this
the emit function is not the one it expects (object broadcast
).
So, I can do:
{ except: player => ({ send : (msg, data) => player.getSocket().broadcast.emit(msg, data) }) }
But that's ugly, especially if the arguments change. So the alternative is this:
{ except: player => ({ send : (t = player.getSocket().broadcast).emit.bind(t) }) }
But is there a more convenient way to do this by assigning a function to an object while keeping it this
as a parent object.
source to share
Using bind
to support scope this
is actually a good solution to your problem, as I see it, it makes the code clearer because you can know which object the function actually belongs to by using apply
or call
when you read the code you don't know, which this
function / method belongs to. Is bind
a pretty good solution to your problem here as far as I know .
source to share