|
|
|
|
|
|
this是JavaScript中常常用到關鍵字,但它在箭頭函數和常規函數中是不同的,因此我們在使用時要知道this在箭頭函數和常規函數中的區別,知道不同后,才能正確使用它。
箭頭函數沒有自己的this
與常規函數不同,箭頭函數沒有自己的this和參數綁定。相反,這些標識符像任何其他變量一樣在詞法范圍內解析。讓我們看一個簡單的例子:
name ="Arrow function"
let me = {
name: "Regular function",
thisInArrow:() => {
console.log("Example of " + this.name); //無 'this' 綁定
},
thisInRegular(){
console.log("Example of " + this.name); //'this' 綁定
}
};
me.thisInArrow();
me.thisInRegular();
輸出
Example of Arrow function
Example of Regular function
與常規函數不同,箭頭函數沒有自己的this。在箭頭函數的情況下,this指的是在定義this箭頭函數的環境中的this值(即“外部”箭頭函數),并且在函數的整個生命周期中保持不變,并且始終綁定到在最近的非箭頭父函數中。
讓我們再看一個簡單的例子:


在函數表達式的情況下,this指的是在createObject內部創建的對象,在箭頭函數的情況下,this指的是createObject自身的this。
無論如何執行或在何處執行,箭頭函數內部的 this 值始終等于外部函數的 this 值。換句話說,箭頭函數可按詞法解析 this,箭頭函數沒有定義自己的執行上下文。
在以下示例中,myMethod() 是箭頭函數 callback() 的外部函數:
const myObject = {
myMethod(items) {
console.log(this); // logs "myObject"
const callback = () => {
console.log(this); // logs "myObject"
};
items.forEach(callback);
}
};
myObject.myMethod([1, 2, 3]); 輸出

箭頭函數 callback() 中的 this 值等于外部函數 myMethod() 的 this。
this 詞法解析是箭頭函數的重要功能之一。在方法內部使用回調時,要確保箭頭函數沒有定義自己的 this:不再有 const self = this 或者 callback.bind(this) 這種解決方法。
箭頭函數沒有自己的參數綁定
參數對象在箭頭函數中不可用,但在常規函數中可用。
常規函數:
let myFunc = {
showArgs(){
console.log(arguments);
}
};
myFunc.showArgs(1, 2, 3, 4);輸出
箭頭函數
let myFunc = {
showArgs : ()=> {
console.log(arguments);
}
};
myFunc.showArgs(1, 2, 3, 4);輸出
總結
本文通過實例介紹了箭頭函數和常規函數的this值的區別,通過本文的學習,我們應該了解到箭頭函數和常規函數的this值的不同之處,在使用中要正確處理。
