What does = () =>
mean in the below code
enterclass Counter extends React.Component {
tick = () => {
...
}
...
} code here
What does = () =>
mean in the below code
enterclass Counter extends React.Component {
tick = () => {
...
}
...
} code here
In your example, it's assigning a function to the tick
variable. The () => { ... }
is the function. It's an ES6-style "arrow" function expression. These are like function
expressions (tick = function() { ... }
) except that the this
value within the function is inherited from the context in which it's defined rather than being set when the function is called.
Here's a simple example of the difference (requires an ES6-enabled JavaScript engine):
var obj = {
method: function() {
var a = ['x'];
snippet.log("this === obj? " + (this === obj));
a.forEach(function() { // Non-arrow function
snippet.log("nonarrow this === obj? " + (this === obj));
});
a.forEach(() => { // Arrow function
snippet.log("arrow this === obj? " + (this === obj));
});
}
};
obj.method(); // this == obj? true
// nonarrow this === obj? false
// arrow this === obj? true
Live Copy on Babel's REPL
Note how the arrow function's this
is the same as this
in the context where it was created, but the non-arrow function's this
isn't (instead, it's set by how forEach
calls it).
It's a feature from ES6 called "arrow function": https://github.com/lukehoban/es6features#arrows
It's basically a shorthand for:
var tick = function () { ... }.bind(this);