I know this sounds like a opinion question, but I'm a Junior in JavaScript skills and would like to understand the technical plusses and minuses of each of the following ways of getting a this
into a function (that has its own this
, of course).
Let's say I write - and this is a real life example of mine -
Calculator.prototype.Initialize = function () {
// Fill in all regions in the RegionsChecked array
this.Data.forEach(function(region){
this.RegionsChecked.push(region.RegionName);
});
…
and I realize that
"Oops, the
this
inthis.RegionsChecked
is supposed to actually refer to theCalculator
function that is calling theIntialize
function."
I either solve this problem by doing
var that = this;
this.Data.forEach(function(region){
that.RegionsChecked.push(region.RegionName);
});
or
(function(calc){
this.Data.forEach(function(region){
calc.RegionsChecked.push(region.RegionName);
});
})(this);
and I'm wondering which would be considered better or if there is an even better way (and why).