一、箭头函数的特点
箭头函数是匿名函数
1. 箭头函数使表达更加简洁,隐式返回值
const isEven = n => n % 2 === 0;
const square = n => n * n;
箭头函数的一个用处是简化回调函数,如下:
// 正常函数写法
[1,2,3].map(function (x) {
return x * x;
});
// 箭头函数写法
[1,2,3].map(x => x * x); //[1,4,9]
2. 没有自己的this
箭头函数中的this实际是外层函数的this(箭头函数的this对象是定义时所在的对象,而不是使用时的对象)
箭头函数最大的一个好处就是它的 this指向定义时所在环境的 this ,而非使用时环境的 this,比如在SetTimeeout 函数的回调函数中,如果使用箭头函数,那么THIS还是指向调用 SetTimeeout 的对象里的this 。
function Timer() {
this.s1 = 0;
this.s2 = 0;
// 箭头函数
setInterval(() => this.s1++, 1000);
// 普通函数
setInterval(function () {
this.s2++;
}, 1000);
}
var timer = new Timer();
setTimeout(() => console.log('s1: ', timer.s1), 3100); // s1: 3
setTimeout(() => console.log('s2: ', timer.s2), 3100); // s2: 0
由于在vue中自动绑定 this 上下文到实例中,因此不能使用箭头函数来定义一个周期方法。箭头函数的this永远指向上下文的this,不能用call()、apply()、bind()这些方法去改变this的指向
3. 箭头函数不能当作构造函数使用、不能使用new
let foo=()=>{
}
var newFoo=new foo()//foo is not a construcotr
4. 不能使用argumetns,取而代之用rest参数...解决
不存在arguments对象
该对象在函数体内不存在。如果要用,可以用 rest 参数代替。
rest形式为(…变量名)可以获取函数的多余参数,并且获取到的是真正的数组对象
arguments只是一个类数组对象,除了length属性和可以使用arguments[0]获取元素之外没有数组的其他特性,可以使用[…arguments]或者Array.prototype.slice.call(arguments,0)、Array.prototype.concat.call(arguments,0)转为数组
let C = (...c) => {
console.log(c);
}
C(1,2,3,3)
5. 箭头函数没有原型对象
没有prototype属性
var foo = () => {
return 1
}
function bar(){
return 2;
}
console.log(foo.prototype) //undefined
console.log(bar.prototype) // {constructor:f}