The arrow function in ES6 simplifies the spelling of the function, the grammar is more readable, and the form is more intuitive. The following describes the arrow writing for single-parameter functions, multi-parameter functions, and non-parameter functions.
1. Single parameter function
//1) 原版
var print = function (obj) {
console.log(obj)
}
print("hello")
//2) 箭头版
var print2 = obj => console.log(obj)
print2("world")
2. Multi-parameter function
//1) 原版
var sum = function (a,b) {
return a+b
}
//2) 箭头版
var sum2 = (a,b) => a+b
//打印
console.log("#1:"+sum(2,3))
console.log("#2:"+sum2(2,3))
3. Function without parameters
let sayhello = () => console.log("hello")
sayhello()
4. Brackets {} wrap multiple lines
var sum3 = (a,b) => {
return a+b
}
let sayHello = () => {
console.log("hello!")
console.log("world!")
}
sayHello()