【问题标题】:Angular 5 this undefined inside array.filterAngular 5 this undefined inside array.filter
【发布时间】:2018-06-20 01:54:53
【问题描述】:

这是我正在尝试的代码

search(){
   this.toDisplay = this.products.filter(function(x){
      return this.checkCondition(x.price, condition);
   }
}

是复杂的条件,如大于、范围、最大值,根据条件数判断条件是否满足,返回真假;

checkCondition(item, condition){
  switch(conditoin){
    case 1:  ... brea;
    case 2:  ... brea;
    case 3:  ... brea;

  }
  return status;
}

问题是当我在过滤器中使用this.checkCondition 时,总是抛出未定义的checkCondition 属性,意味着this 未定义。

我检查了this总是未定义,那么如何调用过滤器内部的函数?

【问题讨论】:

    标签: arrays typescript filter angular5


    【解决方案1】:

    使用arrow function 以便this 自动正确绑定。由于您标记了 TypeScript,因此如果您计划支持仅支持 ES5 及以下版本的浏览器,则可以转换箭头函数:

    search(){
       this.toDisplay = this.products.filter(x => this.checkCondition(x.price, condition));
    }
    

    如果不想使用箭头函数,可以捕获this

    search(){
       var selfRef = this;
       this.toDisplay = this.products.filter(function(x) {
          return selfRef.checkCondition(x.price, condition);
       });
    }
    

    另一种方法是使用bind

    search(){
       this.toDisplay = this.products.filter(function(x) {
          return selfRef.checkCondition(x.price, condition);
       }.bind(this));
    }
    

    【讨论】:

    • 箭头功能还不是所有浏览器都支持,特别是在不同设备上,感谢您的快速回复
    • @AliAdravi 由于您使用的是 TypeScript,因此您实际上不必担心;箭头函数将自动转换为 if you tell it to 支持的任何内容。
    • 你让我很开心,即使在 Type Script 中,我也总是害怕使用箭头功能,非常感谢这一点
    【解决方案2】:

    另一种方法是将“this”分配给过滤器调用之外的局部变量(为此,人们通常使用“that”或“self”作为标识符)。

    例子:

    search(){
       var that = this;
       this.toDisplay = this.products.filter(function(x){
          return that.checkCondition(x.price, condition);
       }
    }
    

    【讨论】:

    • 我实际上在您发布的同时将此作为编辑添加到我的答案中。如果你不能使用箭头函数,这绝对是一个很好的解决方案。不过,您应该添加一个示例。
    猜你喜欢
    • 1970-01-01
    • 2018-11-27
    • 2011-04-19
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 2022-08-08
    相关资源
    最近更新 更多