2.1.2 Arrow function

不論在傳統的函式寫法(fn)或箭頭函式(fn_arr)的寫法,一開始建立 function 的時候 this 所指稱的都是 window 這個物件,然而,如果是使用傳統的寫法,在觸發這個事件時所指稱的對象會從原本的 window 變成 HTMLButtonElement;若使用的是箭頭函式,則會固定所指稱的對象,因此 this 依然指稱的是 window 這個物件。

var button = document.querySelector('button')

var fn_arr = () => {
    //建立function 時this指向window
    console.log(this.constructor.name) //執行function時this指向window
}

var fn = function(){
    //建立function 時this指向window
    console.log(this.constructor.name) //執行function時this指向HTML ButtonElement
}

button.addEventListener('click', fn_arr);

Last updated