在巢狀函數中存取this:解開var that = this;
在JavaScript 中,理解至this 的範圍和值關重要。考慮以下程式碼片段:
function Somefunction() { var that = this; ... }
為什麼要聲明它並為其分配值?
為了理解此技術的目的,讓我們想像一個場景:
var colours = ['red', 'green', 'blue']; document.getElementById('element').addEventListener('click', function() { // this points to the clicked element var that = this; colours.forEach(function() { // this is undefined within this inner function // that still refers to the clicked element }); });
forEach 回呼中的 this 指的是當前數組元素,而不是單擊的元素。但是,這會維護對單擊元素的參考。
當您進入巢狀函數時,其範圍可能會發生變化,從而難以存取原始值。將此別名設為 that 可確保原始值仍可存取。
請注意,將其用作別名並不總是最佳的。最好使用更具描述性的別名,清楚地表明它所指的內容,尤其是在複雜的函數中。
以上是為什麼在巢狀 JavaScript 函數中使用 `var that = this;`?的詳細內容。更多資訊請關注PHP中文網其他相關文章!