I'm learning ES6, I just want to convert my ES5 knowledge to ES6.
here's my ES5 code:
function click() {
this.className += ' grab';
setTimeout(() => (this.className = 'remove'), 0);
};
and here's my ES6 code:
const click = () => {
this.className += ' grab';
setTimeout(() => (this.className = 'remove'), 0);
console.log('RENDERING');
}
My problem is this.className += ' grab'; and setTimeout(() => (this.className = 'remove'), 0); didn't run the function. But console.log shows on the log.
Is this method don't work on arrow functions?
this in regular function always refers to the context of the function being called. However, in the arrow function, this has nothing to do with the caller of the function. It refers to the scope where the function (the enclosing context) is present. That's why we get undefined.
By using arrow functions, we avoid having to type the function keyword, return keyword (it's implicit in arrow functions), and curly brackets.
With normal functions the scoped is bound to the global one by default, arrows functions, as I said before, do not have their own this but they inherit it from the parent scope, in this case the global one.
There's not really enough context to give you a good answer, but one thing stands out. Arrow functions maintain scope, so this
inside function click()
and const click
may well be different. In the ES6 version, this
will refer to whatever was this
during the closure creation, which may not be what you want.
Arrow Functions at MDN clears it up:
An arrow function does not have its own
this.
…Which means that this
will be inherited from the declaring scope.
ES6 arrow functions aren't just a new way of declaring functions, and there's nothing inherently wrong with function myFunction(...)
syntax, nor is it going away. Arrow functions avoid some verbosity when passing a function as an argument (e.g. to forEach
) and avoid the need to rebind a function to a different this
in some cases. Converting all function declarations to arrow syntax is not an upgrade.
In Arrow Functions, this
isn't the this
you would expect. this
in Arrow Functions is defined when you create the function - not when it is called. See here for more information on that.
Thanks to @Jaromanda X from the comments - In this case, keep using standard function notation (function() {...}
) - i.e. just because you bought a new screwdriver, doesn't mean the old hammer isn't still the best tool for banging in nails
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With