Arrow functions are the functions that have a shorter syntax compared to function expressions and arrow function lexically bind the this value. Arrow functions effectively turn function (arguments) { expression } into arguments => expression and are always unspecified. If an expression is used after an arrow, the return is implicit, so no return is required.
The main aim of Arrow Functions is to address and rectify several common pain points of traditional Function Expression:
-
more concise syntax
- and sharing lexical this with the parent scope.
Basic Syntax
(param1, param2, , paramN) => { statements }
(param1, param2, , paramN) => expression
// identical to: => { return expression; }
// Parentheses are optional when there's only one parameter:
(singleParam) => { statements }
singleParam => { statements }
// A function with no parameters requires parentheses:
() => { statements }
Advanced Syntax
// Parenthesize the body to return an object literal expression:
params => ({foo: bar})
// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, , paramN = defaultValueN) => { statements }
// Destructuring within the parameter list is also supported
var f = ([x, y] = [1, 2], {a: z} = {a: x + y}) => x + y + z;
f(); // 6
Lexical this
Each and every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.).
function human() {
// The human() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the human() constructor.
this.age++;
}, 1000);
}
var p = new human();
This issue was fixed by assigning the value in this to a variable that could be closed over.
function human() {
var self = this; // Some choose `that` instead of `self`.
// Choose one and be consistent.
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}
0 Comment(s)