语法:

const aaa = (参数列表) =>{

}

 

1.最普通的箭头函数

非箭头函数写法:
const obj={ function aaa (){ } } 箭头函数: (1)无参数: const aaa = () =>{ }

(2)2个参数
const bbb = (num1, num2) =>{
  return num1 + num2
}

(3)1个参数(括号可以省掉)
const power = num3 =>{
  return num3 * num3
}

 

2.函数中

(1)函数代码块中有多行代码
const aaa = () =>{

    console.log('hello')
    console.log('hello Han Mei')
}

(2)函数中只有一行代码
const mul = (num1, num2) => num1 * num2

调用并打印结果:console.log(mul(2, 32))        ===64 

 

3.this指向

普通函数指向的都是window

箭头函数中的this,引用的是最近作用域中的this

const obj = {

    aaa() {
        setTimeOut(function () {
            console.log(this)   // window   

         })  
       
     // 最近的this是aaa里的this setTimeOut(() =>{ console.log(this) // obj对象 }) } }
const obj = {

    aaa() {
        setTimeOut(function () { 
       setTimeOut(function () {
console.log(this) // window对象
})       
        // 箭头函数找最近的this,最近的this是setTimeOut(function () { ...,所以这里是widow对象
      
setTimeOut(() =>{
console.log(this) // window对象
  })
   })   
      // 最近的this是aaa里的this,所以这里最外层的this是obj
         setTimeOut(() =>{
       setTimeOut(function () {
console.log(this) // window 无论啥时候,普通函数this都指向window
       })       
        // 箭头函数找最近的this,最近的this是setTimeOut(() =>{ ...,所以这里是obj对象
       setTimeOut(() =>{
console.log(this) // obj对象
  })
     }) 
  }
}