3 回答

TA貢獻1863條經驗 獲得超2個贊
您不能將“this”對象作為匿名函數中的參數傳遞。當你這樣做時,如果你認為你有約束力,你就錯了。當您使用Anonymus鍵入函數時,“this”會自動顯示窗口對象,是的。
注1:沒有箭頭函數的構造函數或原型。它不與新的一起使用。目的不是創建對象實例。
注意2:由于2個箭頭函數不會將自己綁定到“this”綁定詞法范圍上下文不會自動綁定自身。
let clicked = () => {
console.log(this) // *"this"* will always show the window object because it was written with arrow function.
}
let clicked = function(){
console.log(this) // *"this"* will show the" p " element. Because bind inte.
}
document.querySelector("#p").addEventListener("click", clicked)
document.querySelector("#p").addEventListener("click", clicked.bind(this)) // If you do bind this way and call the clicked function, which is defined as the arrow function, *"this"* window will show the object.
<p id="p" onclick="myFunc(this)">foo</p> // The reason this works is because it shows the element when you say *"this"*. but the function is in scope if you look at the console.log(this) output, it will show the window object.
function myFunc(el){
console.log(el.innerHTML) // outputs "foo"
console.log(this) //
}
因此,您不能在箭頭函數中重新綁定“this”。它將始終被定義為定義它的上下文。如果你要求這有意義,你應該使用一個普通的函數。
我希望這有點啟示。

TA貢獻1810條經驗 獲得超5個贊
addEventListener eventTarget 需要第二個參數作為 eventHandler 或 jvasrcipt 函數(參見 ref)。因此,如果您將HTML對象作為第二個參數傳遞,您將獲得一個語法錯誤:“缺少正式參數”,并且您的代碼將不會運行(檢查瀏覽器控制臺)。為了回答您的其他查詢,在本例中,這是一個 HTML p 對象。您可以檢查自己:
console.log(this);
console.log(typeof this);

TA貢獻1780條經驗 獲得超1個贊
我以前也有過這樣的疑問。
這主要是因為箭頭函數與普通函數不同,并且在其中一些差異中,“this”在兩者中都受到不同的對待。
“那這個呢?與常規函數相比,箭頭函數對此的處理也不同。簡而言之,使用箭頭函數沒有綁定。在常規函數中,this 關鍵字表示調用函數的對象,可以是窗口、文檔、按鈕或其他任何內容。對于箭頭函數,this 關鍵字始終表示定義箭頭函數的對象。
字體: https://www.w3schools.com/js/js_arrow_function.asp
添加回答
舉報