Bind 'this' to a Class Method obscurity

Bind 'this' to a Class Method obscurity


Tell us what’s happening:

One common way is to explicitly bind this in the constructor so this becomes bound to the class methods when the component is initialized. You may have noticed the last challenge used this.handleClick = this.handleClick.bind(this) for its handleClick method in the constructor. Then, when you call a function like this.setState() within your class method, this refers to the class and will not be undefined.

I think the above is misleading. In a constructor this refers to the new instance being created through the class(constructor). this.handleClick = this.handleClick.bind(this) means "create a prop handleClick on the instance with the value of handleClick(it first doesn’t find it on the new instance being created, but then goes up the prototype chain and finds it in the prototype) and bind the this inside handleClick to the current instance (which in this case doesn’t change anything).

Again, correct me if I’m wrong, but this does not refer to the class/constructor inside the constructor function itself, but rather to the new instance.

Your code so far

class MyComponent extends React.Component {
  constructor(props) {
    this.state = {
      itemCount: 0
    // change code below this line
  this.addItem = this.addItem.bind(this)
    // change code above this line
  addItem() {
      itemCount: this.state.itemCount + 1
  render() {
    return (
        { /* change code below this line */ }
        <button onClick={this.addItem()}>Click Me</button>
        { /* change code above this line */ }
        <h1>Current Item Count: {this.state.itemCount}</h1>

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0.

Link to the challenge:


Yes, the context of this, in this case, is the instance of a class since the class will be instantiated with new keyword at some point.

As to why you’ve posted incorrect code, I have no idea.