使用箭头函数可以省略很多代码,在项目中使用得很频繁,做个笔记总结一些用法。
一、箭头函数,始终指向函数声明时所在作用域下this的值
function getName(){
console.log(this.name)
}
let getName2 = ()=>{
console.log(this.name)
}
window.name = '大脸猫';
const obj = {
name:'蓝猫'
}
getName.call(obj) // 蓝猫
getName2.call(obj) // 大脸猫
举个定时器的栗子:
- 不使用箭头函数需要处理this
let box= document.getElementsByClassName('box')[0];
box.addEventListener("click",function(){
let _self = this; // 保存this的值为当前函数作用域,否则箭头函数会寻找到window下
setTimeout(function(){
_self.style.background = 'lightblue';
},1000)
})
- 使用箭头函数不需要处理this
let box= document.getElementsByClassName('box')[0];
box.addEventListener("click",function(){
setTimeout(()=>{
this.style.background = 'lightblue';
},1000)
})
二、不能作为构造实例化对象
let Person = (name,age)=>{
this.name = name;
this.age = age;
}
let someone = new Person('tony',20);
console.log(someone) // 报错,Person is not a constructor
##### 三、不能使用arguments变量来保存实参
```javascript
let fn = ()=>{
console.log(arguments)
}
fn(1,2) // 报错,arguments is not defined
四、缩写
• 当形参只有一个的时候可以省略小括号
• 当代码体只有一条语句的时候可以省略花括号,此时return必须省略