1.箭头函数作为匿名函数,不能作为构造函数,不能使用new关键字
function Normal(){};
const normal = new Normal(); // 不报错
const Arrow = () => {};
const arrow = new Arrow(); // 报错 Arrow is not a constructor
2.箭头函数没有原型属性,也就是没有prototype属性
const Arrow = () =>{};
console.log(Arrow.prototype); // undefined
3.箭头函数没有自己的arguments,但可以调用外围的arguments
调用自己的arguments
const food = () => {
console.log(arguments) // 报错 arguments is not defined
}
food("鱼", "菜", "饭")
调用外围的arguments
function food() {
const fun = () => {
console.log(arguments[0]); // 鱼
}
fun();
}
food("鱼", "菜", "饭")
ES6的rest参数可用来代替arguments
注:arguments是类数组,rest是真正的数组
const food = (...args) => {
console.log(args) // ['鱼', '菜', '饭']
console.log(args[0]) // 鱼
}
food("鱼", "菜", "饭")
4.this指向不同
普通函数:谁调用这个函数,this指向谁
箭头函数:在哪里定义函数,this指向谁
var name = "小红"
let obj = {
name: "小明",
age: 2,
sayName() {
// 普通函数
setTimeout(function(){
console.log(`我是${this.name}`) // 我是小红
}, 500);
// 箭头函数
setTimeout(() => {
console.log(`我是${this.name}`) // 我是小明
}, 1000);
}
}
obj.sayName()
5.箭头函数不能通过call、apply、bind来改变this的值,但是可以正常传参,只不过是this的指向不受这几个方法的控制
var id = "window"
let obj = {
id: "obj"
}
const fun = (msg) => {
console.log(`${this.id}接收参数${msg}`);
}
// call绑定this指向失败,但是可以正常传参
fun.call(obj, "aaa"); // window接收参数aaa