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(); + }); +});