六、箭头函数
大约 2 分钟约 691 字
ES6
允许使用箭头=>
定义函数
(一)声明并调用
// 声明一个函数
// let fn = function() {}
let fn = (a, b) => {
return a + b;
};
// 调用函数
let res = fn(1, 2);
console.log(res);
// 3
(二)特性
this
是静态的
1. - 始终指向函数声明时所在作用域下的
this
值 - 即箭头函数内部没有自己的
this
,只能往外层找
function getName() {
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
};
// 设置window的name属性
window.name = "ikuko";
const YG = {
name: "IKUKO",
};
// 直接调用
getName();
// ikuko【this直接指向全局作用域this】
getName2();
// ikuko【声明时在全局作用域,this指向window】
// call调用(可以改变函数内部this值)
getName.call(YG);
// IKUKO【this指向“YG”】
getName2.call(YG);
// ikuko【this仍然指向window】
2.不能作为构造函数去实例化对象
let Person = (name, age) => {
this.name = name;
this.age = age;
};
let me = new Person("Chen", 22);
console.log(me);
// Person is not a constructor
arguments
变量来保存实参
3.不能使用 let f = function (a) {
console.log(arguments);
};
f(2);
// Arguments [2, callee: ƒ, Symbol(Symbol.iterator): ƒ]
let fn = () => {
console.log(arguments);
};
fn();
// arguments is not defined
4.箭头函数的简写
1)省略小括号
- 当形参有且只有一个时
2)省略花括号
- 当代码体只有一条语句时
- 此时
return
必须省略,且语句的执行结果就是函数的返回值
let add = (n) => {
return n + n;
};
console.log(add(9));
// 18
let add = (n) => n * n;
console.log(add(9));
// 81
(三)案例实操
1.点击 div,2s 后颜色变为 lightblue
// 获取元素
let ad = document.getElementById("ad");
// 绑定事件
ad.addEventListener("click", function () {
// // 解决this指向报错方法一:保存外层的this值
// let _this = this;
// // 定时器
// setTimeout(function() {
// // 修改背景颜色
// // 报错,this指向window
// // console.log(this);
// // this.style.background = "lightblue";
// // // Cannot set properties of undefined (setting 'background')
// // 解决this指向报错方法一:保存外层的this值
// _this.style.background = "lightblue";
// }, 2000);
// 解决this指向报错方法二:使用箭头函数,this指向外层this值【即事件源ad】
setTimeout(() => {
// 修改背景颜色
this.style.background = "lightblue";
}, 2000);
});
2.从数组中返回偶数的元素
// const arr = [1, 6, 9, 10, 100, 25];
// const result = arr.filter(function(item) {
// if (item % 2 == 0)
// return true;
// else
// return false;
// });
// console.log(result);
// // [6, 10, 100]
const result = arr.filter((item) => item % 2 === 0);
console.log(result);
// [6, 10, 100]
(四)总结
- 箭头函数适用于 与
this
无关的回调- 如:定时器、数组的方法回调
- 不适用于 与
this
有关的回调- 如:
DOM
元素的事件回调、对象的方法
- 如:
- 不适合 !== 不能
// this指向“YG”这个对象
const YG = {
name: "ikuko",
getName: function () {
console.log(this.name);
},
};
// this指向“YG2”外层的this值
const YG2 = {
name: "ikuko",
getName: () => {
console.log(this.name);
},
};