javascript - 使用排序方法在类的比较函数中未定义 this

标签 javascript class ecmascript-6 this undefined

<分区>

我不确定为什么排序方法排序比较函数的第二种情况下的 this 未定义?我设法通过使用箭头函数来纠正这一点。

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);

最佳答案

在这段代码中

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

您的 this 指的是另一个上下文,而不是对象。使用箭头函数代替

this.Inventory.sort( (lhs, rhs) => this.SortedDescending ? rhs.Gold - lhs.Gold : lhs.Gold - rhs.Gold );

关于javascript - 使用排序方法在类的比较函数中未定义 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46193627/

相关文章:

Javascript - 忽略 Switch 语句中的标点符号和空格

javascript - 扩展 Three.js 类

python - 将 View 与模板 View django 合并

javascript - JavaScript 中如何给变量赋值

javascript - 带参数的 onPress 函数运行创建循环

javascript - JavaScript 对象中不同函数声明之间的区别(如果有的话)是什么?

修改数组时的 Javascript 通知

javascript - Phonegap 应用程序中的谷歌地图 V3 使用限制

c# - 在不传递参数的情况下创建新对象

c++ - C++类错误