Don't get mislead by the title, all I'm trying to do is avoding explicity saving of the context with something like self=this
.
What would 'this' be bound to?
this
will be set to the first argument passed in case of.call()/.apply()
.In case of
.bind()
,this
will be the first argument that was passed to.bind()
during the function was creation.On
object.method()
, this will refer to that object.Rest,
this
will reffer to the global context.
Let's see a simple usecase :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
The work around is pretty simple and famous : save the context!
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
But, even more better approach would be to avoid self=this
altogehter and take the advantage of bind()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
This was just a simple use case to make things clear, but this kind of paradigm would be really useful when there are n levels
of nesting. Where one has to save context as that = this
, self = this
and so on... instead bind()
them as per the need!