1

I'm new to React and I'm learning by building a simple test application in which I have a problem with "this" binding. I created this app package yesterday using "create-react-app" so babel and all other plugins should be up to date.

Now about my problem: If i declare a method in a class using an arrow function to bind "this", then everything works fine

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
  }
  someMethod = () => {
    console.log(this);  //"this" works fine
  }
}

But when I try to do the same using explicit "this" binding in a constructor, then binding doesn't work and "this" is undefined:

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
    this.someMethod.bind(this)
  }
  someMethod () {
    console.log(this);  //"this" is undefined
  }
}

Could you please help me to understand why it doesn't work? I read a few articles and chapters in books about "this" binding in JS and in React and I think that both code samples from above should work exactly the same.

0

2 Answers 2

1
class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
    this.someMethod= this.someMethod.bind(this)  //modified this line
  }
  someMethod () {
    console.log(this); 
  }
}

this will work i have make the changes

Sign up to request clarification or add additional context in comments.

Comments

0

When you pass arrow function you don't need to bind this in the constructor. the contructor binding is yor "regular" function.You can use these two codes :

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
  }
  someMethod =  () =>{
    console.log(this); 
  }
}

or

class abc extends Component {
  constructor (props) {
    super(props);
    this.state = {};
 this.someMethod= this.someMethod.bind(this)
  }
  someMethod () {
    console.log(this); 
  }
}

Comments

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.