Angular 5 this undefined inside array.filter

Angular 5 this undefined inside array.filter

这是我正在尝试的代码

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

根据条件数判断大于、范围、最大值等复杂条件,此函数判断条件是否满足,return真或假;

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

  }
  return status;
}

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

我检查过 this 始终未定义,那么如何在过滤器中调用函数?

使用 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));
}

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

示例:

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