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.

+3


source to share


2 answers


You can specify who this

will be by calling the function with apply or call . The first parameter for these methods will be this

inside the function body.



0


source


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 .



0


source







All Articles