I have a class with a member function and a member variable. In the member function, I display the this pointer and it is valid. In the same routine, inside a foreach loop, the this pointer becomes undefined
The code is
public getTypes(vitalsModel) : Array<any>{
var vitals = _.get(vitalsModel, 'data');
if (_.isEmpty(vitals) || !_.isArray(vitals)) {
return [];
}
// the this pointer is valid
_.forEach(vitals, function (vital) {
let setting = _.get(vitalsModel, key);
// here the this pointer is undefined.
this.generalSettings.push(setting);
console.log(keys);
rows.push(keys);
loc++;
});
Anyone sees what i am doing wrong?
Sai Kishore Komanduri
Engineering an eGovernance Product | Hashnode Alumnus | I love pixel art
As a fix, you could assign
thisto another variable, sayself, and use that instead.This should work:
public getTypes(vitalsModel) : Array<any>{ var vitals = _.get(vitalsModel, 'data'); if (_.isEmpty(vitals) || !_.isArray(vitals)) { return []; } // assign the 'this' context to a variable var self = this; _.forEach(vitals, function (vital) { let setting = _.get(vitalsModel, key); // 'this' has a different context here self.generalSettings.push(setting); console.log(keys); rows.push(keys); loc++; }); ...You could read this article to get a good understanding of how
thisworks in JavaScript