3 回答

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
您不能將“this”對象作為匿名函數(shù)中的參數(shù)傳遞。當(dāng)你這樣做時(shí),如果你認(rèn)為你有約束力,你就錯(cuò)了。當(dāng)您使用Anonymus鍵入函數(shù)時(shí),“this”會自動顯示窗口對象,是的。
注1:沒有箭頭函數(shù)的構(gòu)造函數(shù)或原型。它不與新的一起使用。目的不是創(chuàng)建對象實(shí)例。
注意2:由于2個(gè)箭頭函數(shù)不會將自己綁定到“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) //
}
因此,您不能在箭頭函數(shù)中重新綁定“this”。它將始終被定義為定義它的上下文。如果你要求這有意義,你應(yīng)該使用一個(gè)普通的函數(shù)。
我希望這有點(diǎn)啟示。

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

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