First, the grammar
1. Simple function with one parameter
12 |
var single = a => a single( ‘hello, world‘ ) // ‘hello, world‘ |
2. Need to use the parentheses before the arrows for no parameters
123 |
var log = () => { alert( ‘no param‘ ) } |
3. Multiple parameters need parentheses, comma interval between parameters, e.g. two numbers added
12 |
var add = (a, b) => a + b add(3, 8) // 11 |
4. The function body multiple statements need to use curly braces
1234567 |
var
add = (a, b) => {
if
(
typeof
a ==
‘number‘
&&
typeof
b ==
‘number‘
) {
return
a + b
}
else
{
return
0
}
}
|
5. The object needs to be wrapped in parentheses, because the curly braces are accounted for as blocks of code.
1234567 |
var getHash = arr => { // ... return ({ name: ‘Jack‘ , age: 33 }) } |
6. Direct as event handler
123 |
document.addEventListener( ‘click‘ , ev => { console.log(ev) }) |
7. Sort callbacks as arrays
12345678 |
var
arr = [1, 9 , 2, 4, 3, 8].sort((a, b) => {
if (a - b > 0 ) {
return
1
}
else
{
return
-1
}
})
arr
// [1, 2, 3, 4, 8, 9]
|
Second, the attention point
1. The typeof operator is the same as the normal function
12 |
var func = a => a console.log( typeof func); // "function" |
2. Instanceof also returns True, indicating that it is also an instance of function
1 |
console.log(func instanceof Function); // true |
3. This fixed, no longer fickle
12345678910111213 |
obj = {
data: [
‘John Backus‘
,
‘John Hopcroft‘
],
init:
function
() {
document.onclick = ev => {
alert(
this
.data)
// [‘John Backus‘, ‘John Hopcroft‘]
}
// 非箭头函数
// document.onclick = function(ev) {
// alert(this.data) // undefined
// }
}
}
obj.init()
|
This is useful, no more writing me,self,_this, or bind.
4. The arrow function cannot be used with the new
12345 |
var Person = (name, age) => { this .name = name this .age = age } var p = new Func( ‘John‘ , 33) // error |
5. Cannot use argument
1234 |
var func = () => { console.log(arguments) } func(55) // |
For 5, the test in Firefox36 is capable of outputting 55, seemingly without this limitation
Detailed ES6 arrow function