1、上代码
2、什么时候使用箭头函数比较多
const aaa = function () { }
const obj = {
const bbb:function () {}
Es6写法
const ccc = () => {
这里是一个无参的 箭头函数
}
有参数写法
1-1 有两个参数的写法
const ddd = (num1, num2) => {
return num1 + num2
}
1-2 *** 重点 一个参数的 时候 小括号可以省略掉
const eee = num1 => {
return num1 *num1
}
}
2、函数中的代码结构
有多行代码进行使用的在代码块中
const test = () => {
console.log('hello world')
console.log('hello world')
console.log('hello world')
......
}
当我们的代码中只有一行代码的 时候
// const num = ( num1, num2 ) => {
// return num1 + num2
// }
const num = ( num1, num2 ) => num1 + num2
console.log(num(20,10))
这里不需要 return 会直接 返回结果
当我们需要打印一行的结果时候
const conl = () => console.log(' hello world ')
在对象中 使用对象字面量的写法
const obj = {
aaa () {
setTimeout( function () {
console.log(this)
})
setTimeout(() => {
console.log(this)
});
}
}
obj.aaa()
上面的代码 function 中的this 指向的是 window
es6 箭头函数 指向的 this 是 obj.aaa的本身 最近作用域的this
因为会从 log 开始从下往上的查找 this 类使用冒泡