1. 程式人生 > 其它 >箭頭函式及this指向

箭頭函式及this指向

語法:

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物件
  })
     }) 
  }
}