Search code examples
javascriptjavascript-objects

Forcing JavaScript method to use a property of the class instead of a property of the current object in the iteration


I have users array (of objects) inside a JavaScript class. Every user has an isActive property. I have created a setUserStatus that is intended to modify the mentioned property in every user:

class usersGroupMake {

  constructor() {
  
    this.isGroupActive = true;

    this.groups = {
      groupId: 1,
      users: [{
          firstName: 'John',
          lastName: 'Hopkins',
          isActive: true
        },
        {
          firstName: 'Tim',
          lastName: 'Cook',
          isActive: true
        },
        {
          firstName: 'Marry',
          lastName: 'Smith',
          isActive: true
        }
      ]
    };
    
    this.setUserStatus = function(){
      this.groups.users.forEach(function(user) {
        user.isActive = user.isActive && this.isGroupActive;
      });
    }
  }
}

var userGroup1 = new usersGroupMake();
userGroup1.setUserStatus();
console.log(userGroup1.groups.users);

In this function, as you can see, I am trying to use the property isGroupActive of my class but, as far as I can see, JavaScript tries to identify isGroupActive as a property of the current user in the iteration.

What shall I do to be able to use this.isGroupActive from the top of my class insread?

Note: my question is not a duplicate, it is a lot more specific then the question indicated as a dplicate.


Solution

  • You could take thisArg of Array#forEach.

    class usersGroupMake {
    
      constructor() {
      
        this.isGroupActive = true;
    
        this.groups = {
          groupId: 1,
          users: [{
              firstName: 'John',
              lastName: 'Hopkins',
              isActive: true
            },
            {
              firstName: 'Tim',
              lastName: 'Cook',
              isActive: true
            },
            {
              firstName: 'Marry',
              lastName: 'Smith',
              isActive: true
            }
          ]
        };
        
        this.setUserStatus = function(){
          this.groups.users.forEach(function(user) {
            user.isActive = user.isActive && this.isGroupActive;
          }, this); // <--
        }
      }
    }
    
    var userGroup1 = new usersGroupMake();
    userGroup1.setUserStatus();
    console.log(userGroup1.groups.users);