语法:
一、只有一个参数,能够不用写小括号:数组
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