This question already has an answer here:
As in, sometimes when I look at code by other people, they will go var self = this;
or in jquery for example, go var $self = $(this);
is there a particular reason for doing so?
This question already has an answer here:
As in, sometimes when I look at code by other people, they will go var self = this;
or in jquery for example, go var $self = $(this);
is there a particular reason for doing so?
As others have mentioned, you could set a variable to $(this) if you wish to use it in another function.
On practical example would be when doing an ajax call tied to an event on the page. Using JQuery:
or:
One purpose of that would be to make
this
accessible to inner functions. for example:Run it in console to get a sense.
By holding a reference to
this
in some context, you have the ability to access it in other contexts such as within member functions orforEach
loops.Consider the following example:
The particular example (not using JQuery) is the function closure. Referencing this in a function closure refers to the function object, not the context in which the closure was defined. Your example is one way to deal with the closure problem:
Another way to deal with this is with the
apply
method on the function:The first argument in
apply
is the "this
argument" that "this
" will refer too.It preserves the value of
this
for use in functions defined inside the current function.