No 1:簡化書寫
var test = arg1=>arg1;
//單個參數(shù)可以不加小括號
var sum = (arg1,arg2) =>arg1+arg2;
//單行聲明可以不加大括號和return
var sum2 = (arg1,arg2)=>{
return arg1+arg2
}
//多行寫法
var arr = [1, 2, 3, 4];
console.log( arr.filter( val => val%2 == 0)); ? // [2,4 ]
No 2:用來聲明匿名函數(shù)喘蟆,消除傳統(tǒng)匿名函數(shù)的this指向問題
function Person(x){
? ? ?this.name=x;
? ? ?setInterval(()=>{
? ? ? ? ?console.log(this.name)
? ? ?},1000)
}
var man = new Person('xxxj');
//每一秒打印出一個xxxj
轉譯js:
function Person(x) {
var _this = this;
this.name = x;
setInterval(function () {
? ?console.log(_this.name);
? ? }, 1000);
}
var man = new Person('xxxj');