1.箭头函数的声明
// 传统函数的声明
const func1 = function () {
return a + b;
};
function func2() {
return a + b;
}
// ES6
const func3 = (a, b) => {
return a + b;
};
const func4 = (a, b) => a + b;
const func5 = (a) => a + 1;
2.上下文(this)
箭头函数并不会形成独立的上下文,内部 this 指向 window
const studentObj = {
name: "xiaoming",
age: 18,
getName: function () {
console.log(this); // 指向studentObj
console.log(this.name); // xiaoming
},
getAge: () => {
console.log(this); // 指向window
console.log(this.age); //undefined
},
};
箭头函数不能进行 dom 操作
const btn = document.querySelect("#btn");
btn.addEventListener("click", function () {
this.style.color = "grey";
});
箭头函数无法完整使用构造函数,无法使用构造函数的原型方法
// ES5定义构造函数
const Person = function (name, age) {
this.name = name;
this.age = age;
};
const person1 = new Person("xiaoming", "18");
person1; // {name: 'xiaoming', age: '18'}
// 添加原型函数
Person.prototype.getPersonName = function () {
console.log(this.name);
};
person1.getPersonName(); //xiaoming
// 箭头函数
const Animal = (name, type) => {
this.name = name;
this.type = type;
};
const animal1 = new Animal("keke", "dog"); // Uncaught TypeError: Animall is not a constructor
// 添加原型函数报错
Animal.prototype.getAnimalName = function () {
console.log(this.name);
}; // Uncaught TypeError: Cannot set properties of undefined
4.箭头函数的参数特性(箭头函数无法使用 arguments)
const getPersonName = function (name) {
console.log("正常函数", arguments);
};
getPersonName("xiaoming"); //正常函数 Argument['xiaoming']
const getAnimalName = (name) => {
console.log("箭头函数", arguments);
};
getAnimalName("kele"); // Uncaught ReferenceError: arguments is not defined