Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The this keyword not working with arrow functions [duplicate]

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?

like image 858
Doggo Avatar asked Mar 15 '19 04:03

Doggo


People also ask

Why this keyword Cannot be used in arrow function?

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.

What keywords are avoided in arrow functions?

By using arrow functions, we avoid having to type the function keyword, return keyword (it's implicit in arrow functions), and curly brackets.

Do arrow functions have their own binding to the this keyword?

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.


2 Answers

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.

like image 92
adc Avatar answered Sep 25 '22 13:09

adc


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

like image 35
Aniket G Avatar answered Sep 25 '22 13:09

Aniket G