箭头函数:(参数)=>{函数体}
下面来看一道题目
let test = {
name: 'kk',
say: function () {
console.log(this.name, this);
}
}
test.say() //kk {name:'kk',say:f}
test.name = 'xx'
test.say() //kk {name:'xx',say:f}
在ES5中谁调用function,this就指向谁。上述代码中say被test调用,所以this指向test,this.name=test.name。且test的指向是可变的。
若换成ES6的写法
let test = {
name: 'kk',
say: () => {
console.log(this.name, this);
}
}
箭头函数与普通函数对this的指向不同,ES6定义时this指向谁执行的时候this就指向谁。
此时输出的结果this.name为空,this指向window(这里若结果有争议,与eval()有关)。
如何用箭头函数来实现一个数组排序的问题
let arr = [15, 112, 56, 5, 21, 36];
arr.sort((a, b) => a - b);
console.log(arr); //[5, 15, 21, 36, 56, 112]
待补充…