箭头函数和普通函数区别?
- 没有arguments
- 无法通过apply call bind改变this的指向
不适用箭头函数的场景
- 对象方法
- 对象原型
- 构造函数
- 动态上下文的回调函数
- Vue生命周期method中
1、this是静态的
始终指向函数声明时所在作用域下的this的值
直接调用
function getName() {
console.log(this.name);
}
let getName2 = ()=>{
console.log(this.name);
}
window.name = '蜗牛';
const school = {
name:'蜗牛学习'
}
getName() // 蜗牛
getName2() // 蜗牛
通过call调用
可以看出通过call不能改变箭头函数的this指向
function getName() {
console.log(this.name);
}
let getName2 = ()=>{
console.log(this.name);
}
window.name = '蜗牛';
const school = {
name:'蜗牛学习'
}
//通过call方法调用
getName.call(school) //蜗牛学习
getName2.call(school) //蜗牛
2、不能作为构造函数使用
let name = '';
let Person = (name)=>{
this.name = name;
}
let me = new Person('姓名');
console.log(me); //Person is not a constructor Person不是一个构造函数
3、不能使用arguments变量
let fn = () => {
console.log(arguments);
}
fn(1,2,3) //arguments is not defined
4、箭头函数简写
- 省略小括号,当形参有且只有一个的时候
let fn = n => {
console.log(n);
}
fn(1) //1
- 省略花括号,当代码体只有一条语句的时候
let fn = n => console.log(n);
fn(1) //1
let fun = n => n*n
console.log(fun(2));//4
总结: 箭头函数适合于 this 无关的回调、定时器、数组的方法回调。 不适合于 this 有关的回调、事件回调、对象方法。