ES5 this.method is not a function

I have a typescript 2 class that targets ES5. I’m getting the err in the subject line in the console when I run it. The switch statement works fine, but increment() and decrement() methods don’t execute.

class MyClass extends React.Component{
  ...
  increment() {
    console.log('increment()')
    ...
  }
  decrement() {
    console.log('decrement()')
    ...
  }

  buttonClick(btn) {
    console.log(btn)
    switch (btn) {
        case "prev":
            console.log('switch prev')
            this.decrement();
            //this.decrement;
            break;
        default:
            console.log('switch next')
            this.increment();
            //this.increment; eliminates err but method still doesnt execute
            break;
    }
  }
}

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Make sure you bind this to your functions so that the value of this will be what you expect when you call the functions:

class MyClass extends React.Component{
  constructor() {
    super()
    this.increment = this.increment.bind(this)
    this.decrement = this.decrement.bind(this)
    this.buttonClick = this.buttonClick.bind(this)
  }
  increment() {
    console.log('increment()')
  }
  decrement() {
    console.log('decrement()')
  }
  buttonClick(btn) {
    // ...
  }
}

You can also use property initialized arrow functions if you prefer:

class MyClass extends React.Component{
  increment = () => {
    console.log('increment()')
  }
  decrement = () => {
    console.log('decrement()')
  }
  buttonClick = (btn) => {
    // ...
  }
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply