Java Reference
In-Depth Information
This and That
We saw earlier that the value of
this
points to the object calling a method. It allows us to
create generalised methods that refer to properties specific to a particular object. Be aware of
a certain problem when a function is nested inside another function, which can often happen
when using methods in objects, especially ones that accept callback functions. The problem
is that the value of
this
loses its scope and points to the global object inside a nested func-
tion, as can be seen in this example:
superman.allies = [batman,wonderwoman,aquaman]
superman.findFriends = function(){
this.allies.forEach(function(friend) {
console.log(friend.name + " is friends with " +
this.name);
}
);
}
<< "Batman is friends with "
"Wonder Woman is friends with "
"Aquaman is friends with "
It fails to produce the expected output because
this.name
is actually referencing the
name
property of the global
window
object, which in this case is empty so nothing is dis-
played. If strict mode is used, an exception would be thrown (this is a good example of how
a silent fail may not be immediately spotted).
There are a couple of solutions to this problem.
Use
that = this
A simple solution is to set the variable
that
to equal
this
before
the nested function, and
then refer to
that
in the nested function instead of
this
. Here is the example again, using
that
: