初识箭头函数
箭头函数也是一种定义函数的方式,ES6中的函数
1.1 箭头函数的基本使用
定义函数的几种方法以及箭头函数的使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 1.function定义函数
const app = function() {
}
// 2.对象字面量定义
const obj = {
// aaa:function() {
// },
aaa() {
}
}
// 3.ES6方式
// const ccc = (参数列表) => {
// }
// 没有参数,最简单箭头函数
const ccc = () => {
}
</script>
</body>
</html>
1.2 箭头函数的参数和返回值
参数问题
两个参数
const a1 = (num1, num2) => {
return num1 + num2
}
一个参数,括号可以省略
const a2 = num => {
return num * num
}
代码数量问题
一行代码
const a4 = (num1, num2) => num1 + num2
多行代码
括号不能省略
const a3 = () => {
console.log('一行');
console.log('两行');
}
1.3 箭头函数中this的指向
箭头函数的this一层一层向外找
代码测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// setTimeout(function () { // window
// console.log(this);
// }, 1000),
// setTimeout(() => { // window
// console.log(this);
// }, 1000)
const obj = {
aaa() {
setTimeout(function () {
setTimeout(function () {
console.log(this);
})
// 箭头作用域中的this指向的是最近作用域中的this
setTimeout(() => {
console.log(this);
})
})
// 箭头作用域中的this指向的是最近作用域中的this
setTimeout(() => {
setTimeout(function () {
console.log(this);
})
// 箭头作用域中的this指向的是最近作用域中的this
setTimeout(() => {
console.log(this);
})
})
},
}
obj.aaa()
</script>
</body>
</html>