1. 箭头函数写法上更加简单,省略了function关键词
const fn = (val)=> {
return val
}
const arrowFunc = (val) => val
function normalFunc(val){
return val
}
2.arguments 对象
- 箭头函数没有自己的arguments对象
- 普通函数有自己的arguments对象,并能访问传递给函数的所有参数
function normalFunc() {
console.log(arguments);
}
const arrowFunc = () => {
console.log(arguments);
};
normalFunc(1, 2, 3);
arrowFunc(1, 2, 3);
3.this绑定
- 箭头函数
- 没有自己的this,会继承外层作用域的this
- 适用于上下文一致的场景中
- 普通函数
- 有自己的this,取决于调用的对象,谁调用,指向谁
- 如果是用作方法,则指向该对象
- 可以通过bind、call、apply改变this的指向
const obj = {
name: "测试",
arrowFunc: () => {
console.log(this.name);
setTimeout(() => {
console.log(this.name);
}, 100);
},
normalFunc: function() {
console.log(this.name);
setTimeout(function() {
console.log(this.name);
}, 100);
}
};
obj.arrowFunc();
obj.normalFunc();
var id = 'China'
function normalFunc() {
console.log(this.id)
}
const arrowFunc = () => {
console.log(this.id)
}
normalFunc.call({ id: 'Shandong' });
arrowFunc.call({ id: 'Shandong' });
4.构造函数
- 箭头函数不是构造函数,不能使用new关键词
- 没有this
- 没有prototype属性
- new执行了什么?
1.创建了一个新对象
2.将构造函数的prototype指向新对象的__proto__
3.将this指向这个新对象
4.执行构造函数
5.返回这个新对象
- 普通函数可以作为构造函数使用
const ArrowFunc = () => {};
function NormalFunc() {}
new NormalFunc();
new ArrowFunc();
5.prototype属性
const arrowFunc = () => { };
function normalFunc() { }
console.log(arrowFunc.prototype)
console.log(normalFunc.prototype)
6.函数提升
console.log(normalFunc());
console.log(arrowFunc());
function normalFunc() {
return "normal";
}
const arrowFunc = () => "arrow";
7.箭头函数不是Generator函数,不能使用yield关键词