箭头函数的特点:
- this 是静态的,this始终指向函数声明时所在作用域下的this的值
function getName() {
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
}
// 设置window对象的name属性
window.name = '石兴丽';
const school = {
name: 'sxl'
}
// 直接调用
getName(); //石兴丽
getName2();//石兴丽
// 方法调用
getName.call(school); //sxl
getName2.call(school); //石兴丽
2.不能作为构造函数实例化对象
let Person = (name, age) => {
this.name = name;
this.age = age;
}
let me = new Person('xiao', 30)
console.log(me); //报错
3.不能使用arguments变量
let fn = () => {
console.log(arguments);
}
fn(1, 2, 3) //报错
4.箭头函数的简写
1)省略小括号,当形参有且只有一个的时候
let add = (n) => {
return n + n;
}
console.log(add(9)); //18
let add = n => {
return n + n;
}
console.log(add(6)); //12
2)省略花括号,当达玛提只有一条语句的时候,此时return语句也要省略,而且语句的执行结果就是函数的返回值
let pow = (n) => {
return n * n;
}
console.log(pow(9)); //81
let pow = (n) =>
n * n;
console.log(pow(3)); //9
注:箭头函数适合与 this无关的回调,定时器,数组的方法回调箭头函数
不适合与 this有关的回调,事件回调,对象的方法