1、箭头函数基础知识
// 没有参数时,参数的小括号()不可以省略
const fn1_1 = () => {
return 1;
}
// 只有一个参数,可以省略参数的小括号()
const fn1_2 = a => {
return a;
}
const fn2_1 = (a, b) => {
return a + b;
}
// 函数代码块里只有一句返回值:可以省略 { } 大括号 + return
const fn2_2 = (a, b) => a + b;
// 箭头函数只有一行语句,且不需要返回值,可以省略 { } 大括号
const fn2_3 = (a, b) => console.log(a + b);
fn2_3(2, 3); // 5
// 函数代码块里只返回对象组成的数组,可以写成({ })
const arr = ["a", "b", "c"];
const arr1 = arr.map(item => ({ name: item }));
console.log(arr1); // [{"name": "a"}, {"name": "b"},{"name": "c"}]
// 箭头函数可以写剩余参数,不可以写arguments
const fn4 = (...rest) => {
console.log(rest); // [1, 2, 3]
// console.log(arguments); // Uncaught ReferenceError: arguments is not defined
}
fn4(1, 2, 3);
2、箭头函数的this:指向上一层作用域的this
<body>
<button>点击我3秒后变颜色</button>
</body>
<script>
// function的this:指向调用者
function myFunc() {
console.log(this); // window
}
myFunc();
document.querySelector('button').addEventListener('click', function () {
console.log(this); // button
});
document.querySelector('button').addEventListener('click', function () {
setTimeout(() => {
console.log(this); // button
this.style.color = 'red';
}, 3000);
})
总结:如何选择是否使用箭头函数:
1、dom元素注册事件,需要用到this时,就使用function,不要用箭头函数
2、定时器/延时器,需要用到this时,就用箭头函数
3、平时开发,优先选择使用箭头函数,不行再换成function