First, the grammar
1. Simple function with one parameter
| 12 |
varsingle = a => asingle(‘hello, world‘) // ‘hello, world‘ |
2. Need to use the parentheses before the arrows for no parameters
| 123 |
varlog = () => { alert(‘no param‘)} |
3. Multiple parameters need parentheses, comma interval between parameters, e.g. two numbers added
| 12 |
varadd = (a, b) => a + badd(3, 8) // 11 |
4. The function body multiple statements need to use curly braces
| 1234567 |
varadd = (a, b) => { if(typeofa == ‘number‘&& typeofb == ‘number‘) { returna + b } else{ return0 }} |
5. The object needs to be wrapped in parentheses, because the curly braces are accounted for as blocks of code.
| 1234567 |
vargetHash = 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 |
vararr = [1, 9 , 2, 4, 3, 8].sort((a, b) => { if (a - b > 0 ) { return1 } 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 |
varfunc = a => aconsole.log(typeoffunc); // "function" |
2. Instanceof also returns True, indicating that it is also an instance of function
| 1 |
console.log(func instanceofFunction); // 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 |
varPerson = (name, age) => { this.name = name this.age = age}var p = newFunc(‘John‘, 33) // error |
5. Cannot use argument
| 1234 |
varfunc = () => { console.log(arguments)}func(55) // |
For 5, the test in Firefox36 is capable of outputting 55, seemingly without this limitation
Detailed ES6 arrow function