0

does it help in handling the this keyword sometimes, when compared to the normal functions like in ReactJS? Because in react to pass functions through components we need consider the this keyword very carefully so please help me understand how arrow functions help.

Akshay
  • 19
  • 2
  • 1
    The explanations here should clear your doubts: [arrow function vs function declaration expressions](https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – AndrewL64 May 30 '18 at 18:56
  • Yes, it helps, if you understand what they mean. For example when you pass parameters and event to function `onClick={(e) => this.deleteRow(id, e)}` which is equivalent to `onClick={this.deleteRow.bind(this, id)}` – seethrough May 30 '18 at 18:58
  • React is still javascript... – Jonas Wilms May 30 '18 at 19:16

2 Answers2

1

Arrow functions lack scope. For example:

function outer()
{
  function inner()
  {
    console.log(this) //Refers to inner function
  }
  inner();
}

function outerTwo()
{
  let inner = () => {
    console.log(this) //refers to outer
  }
  inner();
}

outer();
outerTwo();

If you try to use an arrow function for a prototype method definition and you use thisanywhere in there, it'll refer to the window / global context.Because it will not have it's own scope. Because they lack scope, they can be useful for method injection, where they can refer to the the container that's calling them. Hence, why they're often used as callbacks.

Eddie D
  • 1,120
  • 7
  • 16
  • This is actually a very clear explanation why arrow functions do not need bind. Another option is a class fields syntax which is sometimes used with currying. – seethrough May 30 '18 at 19:09
0

You answered the question yourself. Using arrow function helps you with referencing this context of the given component and sometimes is also used as it is shorter and therefore faster to write.

user3210641
  • 1,565
  • 1
  • 10
  • 14