<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="btn1">按钮1</button><button id="btn2">按钮2</button>
</body>
<script type="text/javascript">
/**
* 作用: 定义匿名函数
* 基本语法:
* 没有参数: () => console.log('xxx')
* 一个参数: i => i+2
* 大于一个参数: (i, j) => i+j
* 函数体不适用大括号: 只能一些一行代码,或表达式,默认返回执行结果,没有结果返回undefined
* 函数体如果有多个语句,需要使用{}包围,若有返回的内容, 需要手动返回
* 使用场景:
* 多用于定义回调函数
*
* 箭头函数的特点
* 1. 简介
* 2. 箭头函数没有自己的this, 箭头函数的this不是调用的时候决定的,而是在定义的时候处在的对象就是它的this
* 普通函数是,谁调用这个函数,函数内的this就是谁,箭头函数是在谁的内部定义的,this就是谁
* 3. 扩展题解: 箭头函数的this看外层是否有函数
* 如果有,外层函数的this就是内部箭头函数的this
* 如果没有,则this就是window
*/
let fun = () => console.log("this is arrow function!")
/**
* 箭头函数分为两个部分
* => 左边的形参
* 左边的形参对应函数的形参
* => 右边的执行体
* 右边的执行体对应函数的执行体也就是{}包裹的代码
*/
// 左侧形参
// 没有参数 需要写()占位
let paramFun1 = () => console.log('this is arrow function params one!')
paramFun1()
// 有一个形参 可以写() 也可以不写
let paramFun2 = i => console.log('this is arrow function params ',i)
paramFun2('two !')
// 大于一个形参 必须写()
let paramFun3 = (x, y) => console.log(x,y)
paramFun3(10,20)
// 右侧执行体
// 只有一行代码 不是计算表达式,可以不写{} 默认会将执行结果返回,因为不是计算表达式,所以返回结果为undefined
let executeFun1 = (x,y) => console.log(x,y)
console.log(executeFun1(10,20))
// 只有一行代码,是计算表达式,可以不写{},默认会将计算结果返回 30
let executeFun2 = (x,y) => x + y
console.log(executeFun2(10,20))
// 只有一行代码,是计算表达式,写{},不会默认会将计算结果返回,需要手动返回 30
let executeFun3 = (x,y) => { return x + y}
console.log(executeFun3(10,20))
// 多行代码,必须写{},需要手动将结果返回,如果不需要返回结果也可以不返回
let executeFun4 = (x,y) => {
console.log(x,y)
return x + y
}
console.log(executeFun4(10,20))
/**
* 尝试解构对象箭头函数
*/
let obj = {
username: 'flower',
age: 18
}
// 解构对象函数,左侧形参必须写()
let objFun = ({username,age}) => console.log(username,age)
objFun(obj)
// 函数this指向
const btn1 = document.getElementById('btn1')
const btn2 = document.getElementById('btn2')
// 普通函数
btn1.onclick = function(){
// 默认指向调用者
console.log(this)
}
// 箭头函数 默认指向当前所以在作用域 所以是window
btn2.onclick = () => console.log(this)
</script>
</html>