Reputation: 63778
I'm curious why functionA returns an error while functionB has a correct reference to "this" and works. What is the reason for the difference?
class MyComponent extends Component {
...
render() {
return (
<input ref="myInput" type="text" />
<button onClick={this.functionA} />
<button onClick={this.functionB} />
);
}
}
This throws an error "Can't read property 'refs' of undefined:
functionA() {
const val = this.refs.myInput.value;
console.log(val);
}
While this correctly shows the value:
functionB = () => {
const val = this.refs.myInput.value;
console.log(val);
}
Upvotes: 0
Views: 87
Reputation: 2341
In traditional function declaration i.e. function
keyword this
inside function scope refer to the object to which the function belong , or undefined
if there is no hosting object .The point is function
form a new scope different from outside
In new =>
syntax ,there is a different story .the function do not from the new scope (quite different the old way) ,rather,its scope is the same as the outside scope
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Upvotes: 0
Reputation: 22872
In JavaScript function context is defined while calling the function, not while defining it.
You pass both function as callbacks to other component. They are called outside of object they are defined. Thus, they do not share it's class context.
What makes difference here is definition of functionB
. Using arrow function binds current context to underlying function.
You can read more here http://reactkungfu.com/2015/07/why-and-how-to-bind-methods-in-your-react-component-classes/ ... or google more if you are interested.
Upvotes: 1
Reputation: 1573
The difference between the two functions is the use of the arrow expression added on es6 that allow the use of lexycal this.
Until arrow functions, every new function defined its own this
value, preventing you from accessing the correct value.
One of the common workaround is to define a reference to the this on the correct context level and the use it inside your function:
var that = this; //creating a reference to the this we will need in a function
that.refs.myInput.value; // in our function we refer to 'that' variable
Arrow functions instead capture the this
value of the enclosing context, so the this you are referring in FunctionB is actually taken from the "correct" context.
for more information please check: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Upvotes: 1