Wednesday, 1 February 2017

In case of error when arrow function is used


Arrow function in ES6

It is shorter syntax than function expression and it is always anonymous. In Asp.net, arrow function is called lambda expression. This can be called local functions that can be passed as arguments or returned as the value of function calls. Arrow function does not need to use bind().

Basic Syntax


(p1, p2, ..., pN) => { statements }
(p1, p2, ..., pN) => expression // => { return expression; }

(single) => { statements }
single => { statements }

() => { statements }
() => expression // => { return expression; }


Case 1. Callback functions with dynamic context and using global property

"this" keyword is global and allows to change the context which is depends on the means a function is called. It is like "something is happening with this object." So, for dynamic coding, "this" can be efficiently used.

"arrow function" binds the context statically on declaration and is not allowed to use dynamically.

For example, when event listeners are attached to DOM, it is on the client side programming. So, for implementing event listeners, we should use this keyword. Because an event triggers the handler function with this as the target element. Also, when global object/property are using in the code like this, window and others, function() is needed to use instead of using arrow function.


Case 2. Invoking constructors
"arrow function" is not allowed to be used as a constructor due to JS throw an exception.

e.g)
var Example = () => {};
var exp = new Example();  // --> TypeError: Example is not a constructor.

Case 3. Low readability
When the code is toooo short, because arrow function is using too much.

e. g)
let calculate = (a, b) => b === undefined? b=> a*b : a/b;
let result = calculate(6, 3);

This can be changed like below.

function calculate(a, b) {
  if(b === undefined) {
    return function(b) {
      return a * b;
    }
  }
 return a / b;
}

No comments:

Post a Comment