Bind 'this' to a Class Method

·

2 min read

In addition to setting and updating state, you can also define methods for your component class. A class method typically needs to use the this keyword so it can access properties on the class (such as state and props) inside the scope of the method. There are a few ways to allow your class methods to access this 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.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Hello"
    };
    // Change code below this line

    this.handleClick = this.handleClick.bind(this);
    // Change code above this line
  }
  handleClick() {
    this.setState({
      text: "You clicked!"
    });
  }
  render() {
    return (
      <div>
        { /* Change code below this line.Here this.handleClick is returning a bound function and if we put this.handleClick() i.e with parenthesis then it is undefined as it doesnot take it as bound function and behave as it is without binding*/ }
        <button onClick={this.handleClick}>Click Me</button>
        { /* Change code above this line */ }
        <h1>{this.state.text}</h1>
      </div>
    );
  }
};

Always remember The bind() method creates a new function. bind()

Understand better with this example by learning about bind. Also, learn about properties and variables.

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation Object and Properties

let counter={
  num:10,
  getNum:function()
  {
    return this.num;
  }
}

console.log(counter.getNum());
// const getNumValue=counter.getNum;
counter.getNum=counter.getNum.bind(counter);
console.log()
// const BoundgetNumValue=getNumValue.bind(counter);
// console.log(getNumValue());
// console.log(BoundgetNumValue());
console.log(this===window);