No 1:简化书写
var test = arg1=>arg1;
//单个参数可以不加小括号
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:用来声明匿名函数,消除传统匿名函数的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');