語法:
一、只有一個參數,能夠不用寫小括號:數組
var single = a => a; //至關於var single = function(a){return a;}
console.log(single('hello, world'))// 'hello, world'
var single = a => console.log(a); //至關於var single = function(a){console.log(a);}
single('hello, world') // 'hello, world'app
二、沒有參數,要寫一個空的小括號:函數
var noPare = () => console.log("No parameters");
noPare(); //"No parameters"
三、多個參數,參數在小括號中用逗號隔開:ui
var mulPare = (a,b) => console.log(a+b);
mulPare(1,2); // 3
四、函數體有多條語句,用大括號包起來:this
var differ = (a,b) => {
if (a > b) {
return a - b
} else {
return b - a
}
};
differ(5,3); // 2
五、返回對象時須要用小括號包起來,由於大括號被佔用解釋爲代碼塊了:orm
var getObject = object => {
// ...
return ({
name: 'Jack',
age: 33
})
}
六、直接做爲事件,單條語句也要用大括號包起來:對象
form.addEventListener('input', val => {
console.log(val);
});
七、做爲數組排序回調,單條語句也要用大括號包起來:排序
var arr = [1, 9 , 2, 4, 3, 8].sort((x, y) => {
return x - y ;
})
console.log(arr); // 1 2 3 4 8 9
注意:
一、與普通function實例沒有區別,經過 typeof 和 instanceof 均可以判斷它是一個function事件
var fn = a => console.log(a);
console.log(typeof fn); // function
console.log(fn instanceof Function); // true
二、this固定,不須要再多寫一句var _this = this;去綁定this指向get
fruits = {
data: ['apple', 'banner'],
init: function() {
document.onclick = ev => {
alert(this.data)
}
}
}
fruits.init(); // ['apple', 'banner']
三、箭頭函數不能用new
var Person = (name, age) => { this.name = name this.age = age}var p = new Person('John', 33) // error