I have found two answers about it on this site:
- What does .bind(this) work for in Javascript?
- What is the point of using bind(this) in a method in JS?
The problem I see in these answers is that they seem to me to be very focused on the specific use case of the concrete example in which they appear. And they also seem to me that they are not suitable for people like me who are starting (after all, one does not start programming directly with React) On the other hand, if we use good technical documentation such as that of mozilla, I find that I It all seems too technical and abstract. The information I've searched on the internet I think is unclear in the sense that it doesn't explain what problem bind solves . So I wonder if there isn't a super simple explanation that also uses a "Hello World" type example to understand it better.
In the mozilla documentation I mention it says:
The bind() method creates a new function, which when called, assigns its this operator the value given, with a given sequence of arguments preceding any given when the function is called.
The value of this is ignored when the function is called with the new operator.
Let's look at this explanation in parts...
The bind() method creates a new function, which when called, assigns its this operator the given value,
It is not clear to me what this is in relation to bind nor do I know who delivers what to whom, but let's continue...
with a sequence of given arguments preceding any given when the function is called.
I don't know what you mean by "delivered" Who delivers what to whom? And finally:
The value of this is ignored when the function is called with the new operator.
Without understanding what is this
in this movie, they also put this of new
. Why is the lord this
ignored? (With what it has cost me to learn it at this point)
Trying to put it simply,
this
it refers to the execution context, usually,window
or some other factor, such as an event. So even though inside a function you declare properties and methods, itthis
can take different values:When you instantiate a class, you must prefix
new
and you can't use.bind()
because the constructor will always use internallythis
to refer to the instance.By default, all functions are executed under
window
or the function/class where they are defined, unless they are called in another context, such as an event, where it will be necessary to bind what you want to be used asthis
. And it can be any event: click, load, change, input, mouseenter, etc.Also intervals
setTimeout()
andsetInterval()
generate new contexts.When to use
.bind()
?It's simple, when the method or function needs to be executed in a different context, usually triggered by other factors. The main problem lies in identifying these other contexts.
According to the classes example, you can avoid the use of by
.bind()
declaring the methods as arrow functions.Important: I recommend you read about the arrow functions to know why
this
they will always have the context where they were created and you cannot use.bind()
.bind
it serves to transport contexts from one environment to another, or well, technically I define it and understand it like this, but as our dearest friend mozilla tells us in his documentation and as you have already placed in the question:So it is actually a new copy of the original context, however before proceeding to complicate ourselves more it is better to try to understand what it is
this
:What is this?
this
is a reserved word that refers to the current context of the object, in simpler and more specific terms it refers to the instance of a class or the body of an object , in this case it can only be used with objects that havecuerpo
and derive from aprototipo
, usually objectscompuestos
orcomplejos
as can be theclases
, thefunciones
and themetodos
.NOTE: I could have meant anything that is considered a block, where a
bloque
is defined as a space enclosed in curly braces:However, if we take this definition that
this
refers to thebloques
, this definition would be wrong, since for example thebucles
,condicionales
, andobjetos
proper to javascript, despite being able to be delimited between blocks , do NOT have a context, that is, itthis
will beundefined
for each one of them, with which we are left with a definition that will apply only toobjetos compuestos
and that also do not deal with types considered asprimitivos
.If it is still not clear, let's see examples of
this
:In the last part of the code we see how an error appears, and it is that we must take into account that starting from
ES6
there is something called arrow functions, which do NOT have a context, so when trying to invokethis
within an arrow function we would find that itthis
isundefined
.This is a peculiarity of the arrow functions that it is good that you take into account, precisely for this reason it generates the error.
What is bind for and why does it make sense for it to exist?
The use of bind is more frequent in frameworks such as
Angular
,Vue
orReact
since being handled byclases
or tending to use the OOPcomponentes
object-oriented paradigm , a paradigm in which the context can be lost if we do not use it properly.Now, I know that this is going to be a difficult example to understand, but... what would happen if I had some general methods or functions that I wanted to have isolated in a general class or separate file which would later be imported in a file? so that they can be used as if they were natively part of the component's methods?
Well, it turns out that if you try...
THE CONTEXT IS LOST
this
It would no longer refer to the samethis
of the otherclase
orfuncion
what could generate problems that at first you might think are a little strange, for example you would find that when trying to use that method it wouldthis
beundefined
.And watch out... I think that doing the above in this example can be considered a very bad practice since, for example, in the case of angular, there are
providers
other alternatives for that.However, let's ignore this fact and focus on this murky example:
Where the file
globalFunctions.ts
contains:As we see in the second file it is being used
this
, thisthis
is thethis
original of the functiongetToast
which only refers to the code inside curly braces{}
, however as we well know this function does not contain any propertytoastController
associated withthis
:So there is only one option...
That the
this
one we want to refer to is the onethis
of the class of the other file.But then how do we create a quick copy of this method and also configure it to use the one
this
from the class and not the onethis
from the function?bind
is our answer:In this way, the function will no longer use its own context, but rather it will use the context that we have passed to it, which in this case, since it is the class itself, will be able to find the property that we previously defined in the constructor:
bind I think is not really used much... since it should avoid context problems as much as possible, however for cases where you have context problems
bind
it is quite useful.