0

I'm learning to use Classes in Javascript and have run into an issue. I'm unable to access a variable set in my constructor inside of a forEach. Here's what my code looks like:

class Debugger {
    constructor(){
        this.appList = [];
        this.getApps().then(this.processApps);
    }

    getApps(){
        return new Promise((resolve, reject) => {
            System.getAllApplications(function (applicationInfoList) {
                resolve(applicationInfoList);
            });
        });
    }

    processApps(apps){
        apps.forEach(function(app){
            this.appList.push(new Application(app.uuid));
        });
    }
}

The error I get is: Cannot read property 'appList' of undefined, presumably because the this inside my forEach loops is not referencing my class. What is the correct pattern for this?

Ryan Peterson
  • 132
  • 1
  • 9
  • `apps.forEach(app => {` will work as arrow functions don't have their own `this`. – Andy Jan 18 '18 at 14:17
  • The reference to `this` is broken twice: once in `.then(this.processApps)` and once in `apps.forEach(function(app) { ...`. – deceze Jan 18 '18 at 14:18

0 Answers0