作用: 定义匿名函数
基本语法:
没有参数: () => console.log('xxx')
一个参数: (i) => i+2
大于一个参数: (i,j) => i+j
函数体不用大括号: 默认返回结果
函数体如果有多个语句,需要用{}包围,若有需要返回的内容,需要手动返回
使用场景:多用来定义回调函数
箭头函数的特点:
1 简洁
2 箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,而是在定义的时候处在的对象就是它的this
3 扩展理解: 箭头函数的this看外层的是否有函数
如果有,外层函数的this就是箭头函数的this
如果没有,则this就是window
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>箭头函数</title>
</head>
<body>
<button id="btn1">测试箭头函数this_1</button>
<button id="btn2">测试箭头函数this_2</button>
</body>
<script type="text/javascript">
let fun = () => console.log('I am arrow function!')
fun()
// 形参的情况
// 1.没有形参 ()不能省略
let fun1 = () => console.log('I am arrow function!')
fun1();
// 2. 只要一个形参 ()可以省略
let fun2 = a => console.log(a)
fun2('yoona')
// 3. 两个及两个以上
let fun3 = (x,y) => console.log(x,y)
fun3(1,2)
// 函数体的情况
// 1.只有一条语句或者表达式 {}可以省略---会自动返回语句执行的结果或表达式的结果
// let fun4 = (x,y) => x+y // 5
let fun4 = (x,y) => {x+y} // undefined
console.log(fun4(2,3))
// 1.不止一条语句或者表达式 {}不可以省略
let fun5 = (x,y) => {
console.log(x,y)
return x+y
}
console.log(fun5(10,20))
// 测试箭头函数的this
let btn1 = document.getElementById('btn1')
let btn2 = document.getElementById('btn2')
btn1.onclick = function(){// 常规函数
console.log(this)// <button id="btn1">测试箭头函数this_1</button>
};
btn2.onclick = () => console.log(this)// window 此时箭头函数是在全局写的 所处对象为window
// let obj = {
// name : 'Yoona',
// getName(){
// console.log(this) // this指向obj
// btn2.onclick = () => console.log(this) // this指向obj 跟外层函数一样
// }
// }
// obj.getName()
let obj = {
name : 'Yoona',
getName: () => {
console.log(this) // this指向window 因为getName也是箭头函数 其外层没有函数
btn2.onclick = () => console.log(this) // this指向window 跟外层函数一样
}
}
obj.getName()
</script>
</html>