在class的compare函数中使用sort方法未定义它

时间:2017-09-13 09:21:51

标签: javascript class ecmascript-6 this undefined

我不确定为什么在排序方法排序比较函数的第二种情况下这是未定义的?我设法通过使用箭头功能得到了正确的结果。

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

1 个答案:

答案 0 :(得分:1)

在此代码中

this

你的arrow function指的是另一个上下文,而不是对象。请改用this.Inventory.sort( (lhs, rhs) => this.SortedDescending ? rhs.Gold - lhs.Gold : lhs.Gold - rhs.Gold );

</script>

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $(document).ready(function(){
        $('#form').submit(function (e) {
            e.preventDefault(); //**** to prevent normal form submission and page reload

            $.ajax({
                type : 'POST',
                url : '{{route('routeName')}}',
                data : {
                    fname: $("input#fname").val(),
                    lname: $("input#lname").val(),
                },
                success: function(result){
                    console.log(result);
                    $('#head').text(result.status);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    //alert(xhr.status);
                    //alert(thrownError);
                }
            });
        });
    });

</script>