function debounce(fn, delay) {
var timer
return function () {
var context = this
var args = arguments
clearTimeout(timer)
timer = setTimeout(function () {
fn.apply(context, args)
}, delay)
}
}
我很好奇 context = this 在這段代碼中的用途。我不太了解代碼。
其次, fn.apply(context, args) 這部分也不是很好理解。系結這個有特殊原因嗎?您想在整個專案中將 debounce 函式用作 util 函式。
export function debounce(fn, delay) {
var timer;
return function () {
var args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(this, args);
}, delay);
};
}
- 我想知道最后一個和弦和第一個和弦的區別
uj5u.com熱心網友回復:
var context = this
您this
在此代碼中放入不同變數的原因很簡單,
它根據呼叫位置而function(){}
具有不同的值。this
在這種情況下,它setTimeout
作為回呼呼叫,這意味著this
它將是它內部的任何內容,setTimeout
而不是呼叫 debounce 內部函式時的內容
您可以在現代 JavaScript 中使用箭頭函式輕松解決這個問題,它有一個詞法this
-this
基于函式的創建位置而不是呼叫位置。
這將是具有正確this
系結的初始版本的等效代碼。
function debounce(fn, delay) {
var timer
return function () {
var args = arguments
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
fn.apply(context, args)
function#apply
允許您運行一個函式,同時應用特定的this
值以及以符合人體工程學的方式傳遞多個引數。在我們使用rest syntax之前,function#apply
這是唯一的方法,現在您實際上可以fn(...args)
在現代 javascript 中使用(假設您不必顯式系結this
函式的值)。請記住,this
對于幾乎每個人來說,這都是一個令人難以置信的令人困惑的概念。
您通常在定義的函式中系結的原因context
只是這樣debounce
更通用并且更能夠在不同的情況下被呼叫。例如,在這種情況下,我們可以使用this
基于呼叫函式的元素來增加計數器。
在實踐中,您不希望將相同的去抖動功能放在兩者上,您希望擁有一個功能然后對其進行兩次去抖動,否則您最終可能會通過單擊另一個來“取消”對一個功能的單擊,但它是一個很好的例子,說明如何this
使它更實用。
function debounce(fn, delay) {
var timer
return function() {
var args = arguments
clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
const debounced = debounce(function() {
this.dataset.numClicks = (Number.parseInt(this.dataset.numClicks || 0)) 1;
this.innerText = `Clicked ${this.dataset.numClicks} Times!`
console.log(this.innerText)
}, 500);
document.querySelectorAll('button').forEach(el => el.addEventListener('click', debounced));
div {
height: 100%;
width: 100%;
color: black;
background: pink;
}
<button>Click me!</button>
<button>Click me!</button>
uj5u.com熱心網友回復:
當你測驗它時,很容易看出有什么區別。
function debounce1(fn, delay) {
var timer
return function() {
var context = this
var args = arguments
clearTimeout(timer)
timer = setTimeout(function() {
fn.apply(context, args)
}, delay)
}
}
function debounce2(fn, delay) {
var timer;
return function() {
var args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(this, args);
}, delay);
};
}
var button = document.querySelector('button');
button.addEventListener('click', debounce1(function(){console.log("1", this);}, 500));
button.addEventListener('click', debounce2(function(){console.log("2", this);}, 500));
<button>Click</button>
您維護觸發函式與在超時中使用視窗物件的背景關系。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/497313.html
標籤:javascript 反应 打字稿 去抖
上一篇:新手addEventListener樣式CSS全部改<li>
下一篇:錯誤:模塊構建失敗(來自./node_modules/@angular-devkit/build-angular/node_modules/sass-loader/dist/cjs.js)