Search code examples
javascriptecmascript-6ecmascript-harmony

How to access an object member from event callback function in a class object on Ecmascript 6 (ES6)


I've got this :

class Register {

    render(){
        return (<div onchange={this.aFunction}></div>)
    };

    aFunction(event){
        this.printSomething();  //Uncaught TypeError: undefined is not a function
    }

    printSomething(){
        console.log('Horray');
    }

}

How can I call printSomething from within aFunction? Es6 really confuses me.

Thank you.


Solution

  • You'll notice that when using ES6 classes with React a lot has changed.

    Also, ES6 classes don't autobind the way the ES5 React.createClass would.

    As a result, you need to properly bind the this of the function


    You have two options

    1. use an arrow function

    render(){
        return <div onchange={event => this.aFunction(event)}></div>;
    }
    

    2. use a binding

    render(){
        return <div onchange={this.aFunction.bind(this)}></div>;
    }
    

    I assume you're using React.js for this. If you are, you need to update

    class Register
    

    to

    class Register extends React.Component