ES6 can use the arrow to define a function, note that it is a function, and do not define the class (constructor) in this way.
First, the grammar
1. Simple function with one parameter
var single = a + asingle (' Hello, World ')//' Hello, World '
2. Need to use the parentheses before the arrows for no parameters
var log = () = { alert (' No Param ')}
3. Multiple parameters need parentheses, comma interval between parameters, e.g. two numbers added
var add = (A, b) = + A + badd (3, 8)//11
4. The function body multiple statements need to use curly braces
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.
var Gethash = arr = { //... Return ({ name: ' Jack ', age:33 })}
6. Direct as event handler
Document.addeventlistener (' click ', Ev = { console.log (EV)})
7. Sort callbacks as arrays
var arr = [1, 9, 2, 4, 3, 8].sort ((A, b) + = { if (a > 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
var func = a = = Aconsole.log (typeof func); "Function"
2. Instanceof also returns True, indicating that it is also an instance of function
Console.log (func instanceof Function); True
3. This fixed, no longer fickle
obj = { data: [' John Backus ', ' John Hopcroft '], init:function () { Document.onclick = EV = { alert (thi S.data)//[' John Backus ', ' John Hopcroft ' } //non-arrow function //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
var person = (name, age) = { THIS.name = name this.age = Age}var p = new Func (' John ', $)//Error
5. Cannot use argument
var func = () =>{
For 5, the test in Firefox36 is capable of outputting 55, seemingly without this limitation
Related:
http://kangax.github.io/compat-table/es6/
ES6 Arrow function