case 2-Fix this inside closure
Fix this inside closure http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
by shenoyvnm
JavaScript
var user = {
tournament: "anvil",
data: [{
name: "manju",
age: 21
}, {
name: "rajesh",
age: 22
}],
showData: function () {
/* "this" here is correct.the use of this.data here is fine, because "this" refers to the user object, and data is a property on the user object */
console.log(this);
this.data.forEach(function (person){
console.log(this); /** But here inside the anonymous function (that we pass to the forEach method), "this" no longer refers to the user object**/
/** This inner function cannot access the outer function's "this"**/
console.log(person.name + "is participating in" + this.torunament);
});
}
}
user.showData();
/* to fix this have
var theUserObj = this;// in outer function
and use theUserObj in the anonymous function like below
console.log (person.name + " is playing at " + theUserObj.tournament);
})
*/