From 663f3d8c16154d1fae55ce6059e794bad7734597 Mon Sep 17 00:00:00 2001 From: dayongkr Date: Fri, 24 Oct 2025 11:26:57 +0900 Subject: [PATCH] feat(throttle): preserve this context when called as method --- src/function/throttle.spec.ts | 22 ++++++++++++++++++++++ src/function/throttle.ts | 4 ++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/function/throttle.spec.ts b/src/function/throttle.spec.ts index 8808f7f27..d2cfc4817 100644 --- a/src/function/throttle.spec.ts +++ b/src/function/throttle.spec.ts @@ -144,4 +144,26 @@ describe('throttle', () => { expect(callback).toHaveBeenCalledTimes(4); }); + + it('should preserve this context when called as a method', async () => { + const throttleMs = 50; + let capturedMsg: string | undefined; + + const obj = { + msg: 'hello world', + logWithThrottle: throttle(function (this: any) { + capturedMsg = this?.msg; + }, throttleMs), + }; + + obj.logWithThrottle(); + expect(capturedMsg).toBe('hello world'); + + capturedMsg = undefined; + obj.logWithThrottle(); + obj.logWithThrottle(); + + await delay(throttleMs + 1); + expect(capturedMsg).toBe('hello world'); + }); }); diff --git a/src/function/throttle.ts b/src/function/throttle.ts index 9bbae9884..d2a1dc6a5 100644 --- a/src/function/throttle.ts +++ b/src/function/throttle.ts @@ -57,7 +57,7 @@ export function throttle void>( const debounced = debounce(func, throttleMs, { signal, edges }); - const throttled = function (...args: Parameters) { + const throttled = function (this: any, ...args: Parameters) { if (pendingAt == null) { pendingAt = Date.now(); } else { @@ -67,7 +67,7 @@ export function throttle void>( } } - debounced(...args); + debounced.apply(this, args); }; throttled.cancel = debounced.cancel;