1、箭头函数都是匿名函数,无function 声明。
let func = num => {console.log(num)};
func(1) //1
2.箭头函数没有自己的this,它的this继承自其父作用域。
箭头函数的this永远指向其父作用域,任何方法都改变不了,包括call,apply,bind。
//1没有使用箭头函数
const jelly = {
name: "jelly",
hobbies: ['coding', 'sleeping', 'reading'],
printHobbies: function () {
var self = this;
this.hobbies.map(function (hobby) {
console.log(self.name, hobby);
})
}
}
jelly.printHobbies();
//如上,在没有使用箭头函数时,要想调用name值,需要在function中声明self,
// 然后在map()函数中调用self.name才能调用,如果在map()函数中直接调用this,则该map()中的this值为window对象。
//2.使用箭头函数
const Tom = {
name: "Tom",
hobbies: ['coding', 'sleeping', 'reading'],
printHobbies: function () {
this.hobbies.map(hobby => {
console.log(this.name, hobby);
})
}
}
Tom.printHobbies();
// 如上,当使用箭头函数时:this继承自其父作用域,所用this.name能被调用
3.箭头函数不能作为构造函数,不能使用new
const Person = (name, age) => {
this.name = name;
this.age = age;
}
const Bom = new Person("Bom", 18); //Person is not a constructor
// 因为使用箭头函数不能用于构造函数因为箭头函数本身没有属于自己的this,所以箭头函数不可以当做构造函数,
4.绑定事件也不适合使用箭头函数
const div = document.querySelector(".box1");
div.addEventListener("click",()=>{
this.classList.add("in");
setTimeout(()=>{
this.classList.remove("in");
},2000)
})
//默认情况下,click回掉函数会绑定到触发事件的元素上,
//但因为是箭头函数,箭头函数不会绑定到触发事件的元素上,此时this即为外层this,即this为window。
5.当需要使用arguments参数时,不能使用箭头函数,因为 箭头函数没有arguments,caller,callee
const B = (b) => {
console.log(arguments);
}
B(2, 92, 32, 32); // arguments is not defined
6.箭头函数没有原型
const a = () => {
return 1;
}
function b() {
return 2;
}
console.log(a.prototype); // undefined
console.log(b.prototype); // {constructor: ƒ}
总结:
箭头函数优势
1.隐式返回
2.箭头函数都是匿名函数,无function声明
3.箭头函数没有自己的this,它的this继承自其父作用域。
不适宜箭头函数的场景
1.不能作为构造函数
2.定义对象的方法时,不适合使用箭头函数,因为箭头函数中的this值继承自父域,如果使用箭头函数定义对象方法,则this会指定为window。
3.绑定事件也不适合使用箭头函数,默认情况下,click回掉函数会绑定到触发事件的元素上,
但因为是箭头函数,箭头函数不会绑定到触发事件的元素上,此时this即为外层this,即this为window。
4.当需要使用arguments参数时,不能使用箭头函数,因为 箭头函数没有arguments,caller,callee
5.箭头函数没有原型属性