2

Here is the code which I was trying

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

It is complicated condition like greater than, range, max on the basis of condition number, this function decides condition meet or not and return true or false;

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

  }
  return status;
}

Problem is that when i use this.checkCondition inside the filter, always throw checkCondition property of undefined, means this is undefined.

I checked this is always undefined, so how to call a function inside the filter?

2 Answers 2

5

Use an arrow function so that this is automatically bound correctly. Since you tagged TypeScript, you can transpile the arrow functions if you plan on supporting browsers that only support ES5 and down:

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

If you don't want to use arrow functions, you can capture the this:

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

One other method is to use bind:

search(){
   this.toDisplay = this.products.filter(function(x) {
      return selfRef.checkCondition(x.price, condition);
   }.bind(this));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Arrow function still not supported by all the browsers specially on different devices, thanks for you quick reply
@AliAdravi Since you're using TypeScript though, you shouldn't actually have to worry; the arrow function will transpile to whatever is supported automatically if you tell it to.
Man you made my day, I always scared to use the arrow function even in Type Script, A HUGE thanks for this point
0

Another approach is to assign 'this' to a local variable outside the filter call (People commonly use 'that' or 'self' as an identifier for this purpose).

Example:

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

1 Comment

I actually added this as an edit to my answer at the same time you posted. If you can't use arrow functions, this is definitely a good solution. You should add an example though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.