1

I am unsure of why the this in the second case of the Sort methods sort compare function is undefined? I managed to get the correct this by using an arrow function.

var SortTypeEnum = {
  SortByGold: 1,
  SortByOwnership: 2,
};

class Resource {
  constructor(Gold, IsOwned) {
    this.Gold = Gold;
    this.IsOwned = IsOwned;
  }
}

class ResourceInventory {
  constructor(Inventory, SortedDescending = false) {
    this.Inventory = Inventory;
    this.SortedDescending = SortedDescending;
  }

  Sort(sortType) {
    switch (sortType) {
      case SortTypeEnum.SortByOwnership:
        this.Inventory.sort(function (lhs, rhs) {
          return rhs.IsOwned - lhs.IsOwned;
        });
        break;
      case SortTypeEnum.SortByGold:
        this.Inventory.sort(function (lhs, rhs) {
          return this.SortedDescending ? rhs.Gold - lhs.Gold : lhs.Gold - rhs.Gold;
        });
        this.SortedDescending = !this.SortedDescending;
        break;
    }
  }
}

var resources = [new Resource(1, false), new Resource(3, false), new Resource(2, true)];

var inv = new ResourceInventory(resources);

inv.Sort(SortTypeEnum.SortByGold);
Ognyan M
  • 94
  • 7
  • 2
    The sort-callback does not get `this` bound to what you think. See referenced Q&A. One solution: define that callback as an arrow function. – trincot Sep 13 '17 at 09:25
  • 1
    Use an arrow function, or read the flag once in a local variable outside the `sort` and then use that. – T.J. Crowder Sep 13 '17 at 09:26

1 Answers1

1

In this code

this.Inventory.sort(function (lhs, rhs) {
    return this.SortedDescending ? rhs.Gold - lhs.Gold : lhs.Gold - rhs.Gold;
});

your this refers to another context, not the object. Use arrow function instead

this.Inventory.sort( (lhs, rhs) => this.SortedDescending ? rhs.Gold - lhs.Gold : lhs.Gold - rhs.Gold );
Suren Srapyan
  • 57,890
  • 10
  • 97
  • 101