一、前言
本篇文章是关于js高级知识点梳理的第二篇,会谈到有关于箭头函数的知识点。箭头函数如何简写,以及箭头函数中的this指向,都是在应用中非常值得我们注意的问题。
二、箭头函数
箭头函数的存在能够使得回调函数更简单。
什么是回调函数?回调函数就是一个被作为参数传递的函数,如forEach()
,setTimeout()
。
1.1、基本语法
ES6 允许使用 “箭头”(=>)简化函数的定义。
箭头函数本质也是函数,它出现的目的是为了让我们在使用回调函数的时候更简单
固定语法:
(参数) => { 函数体 }
例如:
// 1. 函数表达式 匿名函数赋值给变量
let fn1 = function(){}
let fn1 = ()=>{} 箭头函数赋值给一个变量
setTimeout(() => {
console.log(111);
}, 2000)
// 2. 正经(普通)的函数 也不用箭头函数
// let fn1 = () => { }
// function fn1(){
// }
var arr = [10, 20, 30];
arr.forEach((item) => {
console.log(item);
})
注意点:
1、函数体只有一句话,可以省略{}不写;
2、函数体只有一句话,并且要返回一个结果, 可以省略return不写;
3、函数参数只有一个,可以省略()不写;
4、多个参数,多行代码不能简写;
5、不能使用arguments参数,可以使用 rest 参。
6、返回一个对象,不能简写。
代码示例:
// 1. 创建一个无参无反函数
let fn1 = () => console.log("fn1");
fn1();
// 2. 创建一个无参有反函数
let fn2 = () => "fn2";
console.log(fn2());
// 3. 创建一个有参无反函数
let fn3 = a => console.log(a);
fn3("fn3");
// 4. 创建一个多参数,多行代码的 函数
let fn4 = (a, b) => {
let sum = a + b;
return sum;
}
console.log(fn4(1, 3));
// 5. 箭头函数中使用 arguments
let fn5 = (...rest) => {
// console.log(arguments);
console.log(rest);
}
fn5(10, 20, 30);
// 6. 返回一个对象-----不能简写
// 预期的返回数据类型 {x:参数a,y:参数b}
// 函数有{} 对象也有{} ----- 会将对象的{}看做是函数的{}
let fn6 = (a, b) => {
return { x: a, y: b };
};
console.log(fn6(1, 2));
1.2、箭头函数中的this
this指向总结:
1、 全局使用(函数全局调用)指向window;
2、 对象调用指向该对象(事件中的事件源);
3、 箭头函数没有自己的作用域,即箭头函数this指向其外层作用域。
// 目的: 总结 碰到的 this 指向
// 1. 全局使用 ----- 默认状态 this指向window
// console.log(this);// 不会这么用
/* function fn() {
console.log(this);
}
fn(); */
// 2. window.setTimeout 定时器中使用 this指向window
/* setTimeout(function () {
console.log(this);
}, 1000) */
// 3. 对象方法的使用--------this指向该对象
let obj = {
// 对象的属性
name: "欧阳三",
age: 20,
_this: this,
// 对象的方法
/* eat: function () {
console.log("爱吃臭豆腐盖浇饭");
console.log(this);
},
sleep() {
console.log("上课不睡觉");
console.log(this);
}, */
// 4. 箭头函数中使用this--------- 指向外层作用域
eat: () => {
console.log("爱吃臭豆腐盖浇饭");
console.log(this);
}
}
obj.eat();
// obj.sleep();
console.log(obj._this);
在dom操作中使用箭头函数:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: #cfc;
}
</style>
</head>
<body>
<h3>案例-箭头函数中使用this</h3>
<div id="box">
</div>
<script>
// 需求: 点击盒子,1s之后,改变自己的宽度
var _box = document.getElementById("box");
/* // ES5解决方案 存储this
_box.onclick = function () {
// console.log(this);
var _this = this;//
window.setTimeout(function () {
// this.style.width = "300px";
// //定时器中的this指向window
// console.log(this.style);
// console.log(this);
_this.style.width = "300px";
}, 1000)
} */
//ES6解决方案
_box.onclick = function () {
window.setTimeout(() => {
console.log(this);
// 使用了箭头函数, this ***指向了外层作用域***-----点击事件----this指向事件源
this.style.width = "300px";
}, 1000)
}
</script>
</body>
</html>
三、总结
这就是本篇文章对箭头函数的简单讲解和分析了。今天其实还需要整理一下Promise对象的相关知识点,但以前已经整理过了,故在这篇文章不再赘述。详情可见Promise对象详解(涉及回调地狱的解决、async&await的使用)。