0

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.

SudoPlz
  • 14,037
  • 8
  • 67
  • 100

2 Answers2

4

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
Thank you
  • 107,507
  • 28
  • 191
  • 224
  • I am, thank you for your answer, and don't worry my class is much more complex than this, I just simplified it and forgot to add the extension here. – SudoPlz Jul 01 '15 at 21:24
0

I think the problem is that this on render is bound on the div.

var foo = new Register;
var div = foo.render();
div.onchange(); // this is div, not foo
foo.aFunction(); // doesn't throw TypeError.
Skydda
  • 156
  • 3