ES6 can use the arrows to define a function, note that it is a function, and do not define a class (constructor) in this way. =>
First, the grammar
1. Simple function with one parameter
var single = a => a
("Hello, World")//' Hello, World '
2. No parameters need to be used before the arrow plus parentheses
var log = () => {
alert (' no param ')
}
3. Multiple parameters need to use parentheses, the comma interval between parameters, such as two numbers added
var add = (A, b) => A + B
Add (3, 8)//11
4. Function body multiple statements need to use curly braces
var add = (A, b) => {
if (typeof a = = ' number ' && typeof b = = ' number ') {return
A + b
} else { C17/>return 0
}
}
5. When returning an object, it needs to be wrapped in parentheses because the braces are occupied and interpreted as blocks of code.
var Gethash = arr => {
//...
Return ({
name: ' Jack ',
age:33
})
}
6. Direct as an event handler
Document.addeventlistener (' Click ', Ev => {
console.log (EV)
})
7. Sort callback as Array
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, pay attention to the point
1. The typeof operator is the same as a normal function
var func = a => a
console.log (typeof func);//"function"
2. Instanceof also returns True, indicating that it is also an instance of a function
Console.log (func instanceof Function); True
3. This fixed, no longer capricious
obj = {
data: [' John Backus ', ' John Hopcroft '],
init:function () {
Document.onclick = EV => {
alert (thi S.data)//[' John Backus ', ' John Hopcroft ']
}
//non-arrowhead function
//Document.onclick = function (EV) {
// Alert (this.data)//undefined
//}
}
Obj.init ()
This is useful, no more writing me
, self
_this
or bind
.
4. Arrow functions cannot be used with new
var person = (name, age) => {
this.name = name
This.age = Age
}
var p = new Func (' John ',%)//Err Or
5. Cannot use argument
var func = () => {
console.log (arguments)
}
func (55)//
For 5, the test in Firefox36 can output 55, seemingly without this restriction
Third, summary
The above is all about the arrow functions in the ES6, I hope for everyone the arrow function in the ES6 can help. If you have questions, you can leave a message for discussion.