0

I am trying to understand the below piece of code

this.handleFilterTextChange = this.handleFilterTextChange.bind(this);

in the snippet below (taken from Reacts official site)

class SearchBar extends React.Component {
  constructor(props) {
    super(props);
       this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
  }

  handleFilterTextChange(e) {
    this.props.onFilterTextChange(e.target.value); // props will give undefined unless we bind this method in the constructor.
  }


  render() {
    return (
      <form>
        <input
          type="text"
          placeholder="Search..."
          value={this.props.filterText}
          onChange={this.handleFilterTextChange}
        />
      </form>
    );
  }
}

I am aware of the bind() upto some extend, this is not a question of usage of the bind(). I am confused because this.handleFilterTextChange is already in the context and why is there a need to bind it again to 'this', why does the this.props not accessible outside the constructor unless the method it is contained in is not bound to this?

Tinu Jos K
  • 888
  • 1
  • 8
  • 21
  • @VLAZ, actually i am confused in that particular code, i guess i am aware of the usage of 'this' and 'bind' to some extend. – Tinu Jos K Feb 05 '20 at 07:58
  • 1
    If you *execute* `this.foo()` directly, then you get the function running with `this` as its context. However, if you pass this as a function reference and executed it (e.g., an event handler) what you are doing is essentially `f = this.foo; f()` When executed *that way*, you get a context of either `undefined` or `window` depending on whether you're in strict mode or not. – VLAZ Feb 05 '20 at 08:00
  • ok so you are saying that the 'this' inside the bind in my example has some other context (may be from the component which called 'SearchBar') other than the context of the class SearchBar. – Tinu Jos K Feb 05 '20 at 08:04
  • this.handleFilterTextChange.bind(this) ---- this line confuses me a lot, how does the first 'this' and last 'this' be different? and if not, why are we setting the same context again? it could be a stupid question, but i am confused. – Tinu Jos K Feb 05 '20 at 08:06
  • Not at all. Let's clarify - *methods don't have a context*. The fact that you have `this.foo = function() {}` doesn't mean anything when it comes to context. You just have some function assigned to some property. Context is determined *at the time you call something*. So, if you invoke `foo.bar()` you call `bar` with `this = foo` but if you do `baz = foo.bar; baz()` you call `baz` (which is the same as `foo.bar`) but now `this = undefined`. I urge you to look at [How does the “this” keyword work?](https://stackoverflow.com/q/3127429) which explains it in more detail. – VLAZ Feb 05 '20 at 08:08
  • ok thanks much@VLAZ, i will have a look at it. – Tinu Jos K Feb 05 '20 at 08:09

0 Answers0