0

I have a typescript class and it has a member function and a member variable. Before a forEach loop, I can check the this pointer and it is valid. Inside the loop, when I refer to it, it is null.

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 null.
        this.generalSettings.push(setting);

        console.log(keys);
        rows.push(keys);
        loc++;
    });

    return rows;
}

Can anyone explain this to me?

qxz
  • 3,697
  • 1
  • 11
  • 29
reza
  • 4,958
  • 14
  • 66
  • 102
  • 1
    Please use standard `// code comments` to add inline code descriptions. –  Feb 07 '17 at 00:00
  • I don't know what `_` is referring to in your code, but in standard `forEach` implementations, you can pass an object as the second argument to set the `this` value. So `_.forEach(vitals, function(vital) { ... }, this)`. –  Feb 07 '17 at 00:03
  • Or just use an arrow function. `_.forEach(vitals, vital => { ... })` –  Feb 07 '17 at 00:04
  • 1
    The issue comes down to understanding how `this` works in JS, but with arrow functions, it's a non-issue, since they don't define a `this`, so it uses the value that it closed over. –  Feb 07 '17 at 00:05
  • Since you're using typescript, just go for `for (var vital of vitals)` – Bergi Feb 07 '17 at 00:21

0 Answers0