如何从ES6转换为ES5(箭头功能)

时间:2019-05-21 01:58:50

标签: javascript ecmascript-6 sapui5 ecmascript-5

我正在尝试将ES6箭头功能转换为ES5

我已经尝试更改它,但是由于我正在使用this.getView()

,它失去了作用域
this.getModel().read('/CharacteristicSet', {
  filters: this._afilters,
  success: function (oData) {
    oViewModel.setProperty('/charSet', oData.results);

    for (let i = 0; i < oData.results.length; i++) {
      if (oData.results[i].GroupId === sKey) {
        oBinding.filter(this._mFilters[sKey]);
      }
    }

    let aIconTabItems = this.byId('iconTabBar').getItems();
    let aCharacteristics = oData.results;

    for (var j = 0; j < aIconTabItems.length; j++) {
      let count = aCharacteristics.filter(
        obj =>
          obj.GroupId === aIconTabItems[j].getKey() &&
          obj.EquipmentNumber ===
            this.getView()
              .getBindingContext()
              .getProperty('EquipmentNumber'),
      ).length;

      oViewModel.setProperty(`/${aIconTabItems[j].getKey()}`, count);
    }
  }.bind(this),
});

我希望它是ES5

1 个答案:

答案 0 :(得分:1)

一种可能的解决方案是使用Array.filter()中的thisArg

  

thisArg :可选-执行回调时用作this的值。

特别是谈到您要转换的箭头功能,您可以传递this回调中的success上下文,以在this的filter()中使用:

var count = aCharacteristics.filter(function(obj)
{
    var equipmentNum = this.getView().getBindingContext().getProperty("EquipmentNumber");
    return obj.GroupId === aIconTabItems[j].getKey() && obj.EquipmentNumber === equipmentNum;
}, this /* Here we use the thisArg of filter */).length;

另一种方法是,仅在loop之外定义一个变量,就像对变量aIconTabItems所做的那样:

let aIconTabItems = this.byId('iconTabBar').getItems();
let aCharacteristics = oData.results;
let equipmentNum = this.getView().getBindingContext().getProperty('EquipmentNumber');

for (var j = 0; j < aIconTabItems.length; j++)
{
    let count = aCharacteristics.filter(function(obj)
    {
        return obj.GroupId === aIconTabItems[j].getKey() &&
               obj.EquipmentNumber === equipmentNum;
    }).length;

    oViewModel.setProperty(`/${aIconTabItems[j].getKey()}`, count);
}