一. 箭头函数
+ 一种新的函数定义方式
+ 对于函数表达式的简写方式(匿名函数)
+ 匿名函数
=> var fn = function(){}
=> var obj = { fn: function(){} }
=> setTimeout( function(){}, 0)
=> setInterval( function(){}, 0)
=> [].forEach( function(){} )
=> div.onclick = function(){}
=> div.addEventListener('click', function(){})
=> ...
+ 语法: () => {}
=> (): 形参的位置
=> =>: 箭头函数的标志
=> {}: 代码段
var fn = function(){
console.log('我是一个函数')}
fn()
var fun = (a, b) => {
console.log('我是一个 fun 函数')
console.log(a)
console.log(b)
}
fun(100, 200)
![在这里插入图片描述](https://img-blog.csdnimg.cn/a5a42b482d36470f887d8857e507fc96.png#pic_left)
箭头函数的特性
1. 箭头函数如果只有一个形参
=> 那么可以省略小括号不写
=> (a) => {}
-> a => {}
2. 箭头函数代码段里面只有一句话, 可以省略大括号和 return 不写
=> 并且会自动 return 这一句话的结果
=> () => { return 123 }
=> () => 123
3. 箭头函数里面没有 arguments
=> 压根没有, 用不了
4. 箭头函数里面没有 this 关键字
=> 官方解释: 箭头函数里面的 this 是 上下文(context), 外部作用域的 this 就是箭头函数内的 this
=> 私人解释: 你的箭头函数定义在哪一行, 上一行的 this 就是 箭头函数里面的 this
5. 箭头函数里面的 this 任何方法都改变不了
=> 因为箭头函数没有 this
=> call / apply / bind 不能改变箭头函数的 this 指向
let fn = (a) => {
console.log(a) }
let fun = a => {
console.log(a) }
fn(100)
fun(200)
let arr = [10, 20, 30, 40, 50]
let res = arr.every( function(item){
return item >= 10} )
let res2 = arr.every(item => {
return item >= 10} )
console.log(res, res2)
![在这里插入图片描述](https://img-blog.csdnimg.cn/4819258504d54bd7aaa59f37d8a7d320.png#pic_left)
let fn = (a, b) => {
return a + b }
console.log(fn(10, 20))
let fun = (a, b) => a+b
console.log(fun(20, 30))
let arr = [10, 20, 30, 40, 50]
let res3 = arr.every(item => item >= 10)
console.log(res3)
![在这里插入图片描述](https://img-blog.csdnimg.cn/231872294c854376ad7d230053e95edd.png#pic_left)
let fun = function(){
console.log(arguments) }
let fn = () => {
console.log(arguments) }