Angular 5 array.filter 内未定义

Ali*_*avi 2 arrays filter typescript angular5

这是我正在尝试的代码

search(){
   this.toDisplay = this.products.filter(function(x){
      return this.checkCondition(x.price, condition);
   }
}
Run Code Online (Sandbox Code Playgroud)

它是基于条件数的大于、范围、最大值等复杂条件,该函数判断条件是否满足并返回 true 或 false;

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

  }
  return status;
}
Run Code Online (Sandbox Code Playgroud)

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

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

zer*_*298 5

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

search(){
   this.toDisplay = this.products.filter(x => this.checkCondition(x.price, condition));
}
Run Code Online (Sandbox Code Playgroud)

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

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

另一种方法是使用bind

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