It is very common to use anonymous functions as parameters in JavaScript. Event binding, async callback and so on all use anonymous function. ES6 introduced new Arrow Functions which has shorter syntax as a replacement for anonymous function. The basic syntax is: (arguments) => {expression or return value}
.
Syntax
Parentheses around the argument list can be skipped if there is only one argument:
a => a * 2
// Is equivalent to:
function (a) {
return a * 2;
}
Parentheses cannot be skipped if there is no argument or multiple arguments:
() => true
// Is equivalent to:
function () {
return true;
}
(a, b) => a + b
// Is equivalent to:
function (a, b) {
return a + b;
}
In the code snippet above, {...}
and return
were skipped because the return value was simply an expression. If the function is complicated, then we still need {...}
and return
to contain function statements:
$('button').click(event => {
doSomething();
doSomethingElse();
});
// Is equivalent to:
$('button').click(function(event) {
doSomething();
doSomethingElse();
});
Remember to wrap the object literal in parentheses:
a => ({})
// Is equivalent to:
function (a) {
return {};
}
this
Unlike ordinary functions, an arrow function does not create its own this
context, so this
has its original meaning from the enclosing context. Take a look at following code:
var Person = function(name) {
this.name = name;
this.sayNameAfterTwoSeconds = function() {
var me = this;
setTimeout(function() {
alert(me.name);
}, 2000);
}
};
var john = new Person('John');
john.sayNameAfterTwoSeconds();
The caller of setTimeout
is window
, thus the inside anonymous function defines the this
value as window
. In old way, we solve this problem by assigning the value in this
to a variable that could be closed over. Now, arrow functions perfectly solve this problem:
var Person = function(name) {
this.name = name;
this.sayNameAfterTwoSeconds = function() {
setTimeout(() => {
alert(this.name)
}, 2000);
};
};
var john = new Person('john');
john.sayNameAfterTwoSeconds();