Java Reference
In-Depth Information
superman.findFriends = function(){
that = this;
this.allies.forEach(function(friend) {
console.log(friend.name + " is friends with " +
that.name);
}
);
}
superman.findFriends();
<< "Batman is friends with Superman"
"Wonder Woman is friends with Superman"
"Aquaman is friends with Superman"
You might also see self or _this used to maintain scope in the same way.
Use bind(this)
The bind() method is a method for all functions and is used to set the value of this in
the function. If this is provided as an argument to bind() while it's still in scope, any
reference to this inside the nested function will be bound to the object calling the original
method:
superman.findFriends = function() {
this.allies.forEach(function(friend) {
console.log(friend.name + " is friends with " +
this.name);
}.bind(this)
);
}
superman.findFriends();
<< "Batman is friends with Superman"
"Wonder Woman is friends with Superman"
"Aquaman is friends with Superman"
Search WWH ::




Custom Search