js 中关于更改 this 指向的问题
在 javascript 中,this 关键字始终指向调用方法或函数当前的执行上下文对象。然而,在某些情况下,可能需要动态更改 this 的指向。
考虑如下的防抖函数:
function debounce(func, wait, immediate) { let timer; return function() { let context = this, args = arguments; if (timer) clearTimeout(timer); if (immediate) { let callNow = !timer; timer = setTimeout(() => { timer = null; }, wait); if (callNow) func.apply(context, args); } else { timer = setTimeout(() => { func.apply }, wait) } } }
在该函数中,使用了 apply 方法。apply 有两个主要作用:
因此,在防抖函数中,apply 方法用于更改 this 指向为当前执行上下文对象,并传递作为参数传递的所有参数。