Why this is bound explicitly

Tell us what’s happening:

Hey so I’m not having trouble with the code per se I was just wondering if someone might clarify why the this keyword isn’t explicitly bound to the handleClick method already since it is a method of this specific class. I assumed a this keyword used inside a javascript class would automatically point to the class in which it is contained. How come that is not the case?

Your code so far

class MyComponent extends React.Component {
constructor(props) {
  this.state = {
    text: "Hello"
  // change code below this line
  this.handleClick = this.handleClick.bind(this);
  // change code above this line
handleClick() {
    text: "You clicked!"
render() {
  return (
      { /* change code below this line */ }
      <button onClick={this.handleClick}>Click Me</button>
      { /* change code above this line */ }

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Bind ‘this’ to a Class Method

Link to the challenge:

Heyyy, maybe this link will give you the insights you need…

Thank you for the share! This article was very helpful!

You are welcome, helped me understand better, you shouldalso read more on how this behaves in vanilla javascript too, to strengthen the knowledge

1 Like