<分区>
我不确定为什么排序方法排序比较函数的第二种情况下的 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);