this
refers to the scope of the anonymous function in which it resides, which would be window.
var sport = {
players: [1, 2, 3],
show: function() {
this.players.forEach(function(entry) {
console.log(entry);
// this refers to the scope of the anonymous function, which is window
console.log(this);
});
}
}
//sport.show();
var sport2 = {
players: [3, 4, 5],
show: function() {
// this refers to the object scope in which it resides -
// in which case, that would be "sport2"
var self = this;
this.players.forEach(function(entry) {
console.log(entry);
// self is now synonymous with "this" in the sport2 scope.
console.log(self);
});
}
}
sport2.show();
Edit: self could be set inside of the show
function itself, no need to pass it in the ugly way. Thanks to the comment section for pointing this out.