From 95eef872be4d812c129fcc976caddc0a3446b5e6 Mon Sep 17 00:00:00 2001 From: Sindre Sorhus Date: Wed, 15 Nov 2023 20:30:08 +0700 Subject: [PATCH] Protect against improper use in classes Fixes #8 --- index.js | 4 ++++ test.js | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/index.js b/index.js index bbc1e73..bdd851f 100644 --- a/index.js +++ b/index.js @@ -24,6 +24,10 @@ function debounce(function_, wait = 100, immediate) { } const debounced = function (...arguments_) { + if (storedContext && this !== storedContext) { + throw new Error('Debounced method called with different contexts.'); + } + storedContext = this; // eslint-disable-line unicorn/no-this-assignment storedArguments = arguments_; timestamp = Date.now(); diff --git a/test.js b/test.js index c31d43c..d2114e0 100644 --- a/test.js +++ b/test.js @@ -173,3 +173,28 @@ describe('forcing execution', () => { expect(callback.args[2]).toEqual([1]); }); }); + +describe('context check in debounced function', () => { + it('should throw an error if debounced method is called with different contexts', () => { + function MyClass() {} + + MyClass.prototype.debounced = debounce(() => {}); + + const instance1 = new MyClass(); + const instance2 = new MyClass(); + + // Call the debounced function on the first instance + instance1.debounced(); + + let errorThrown = false; + try { + // Attempt to call the same debounced function on a different instance + instance2.debounced(); + } catch (error) { + errorThrown = true; + expect(error.message).toEqual('Debounced method called with different contexts.'); + } + + expect(errorThrown).toBeTruthy(); + }); +});