on-internet
← Community

How can a singleton class have static methods that call instance methods?

Stack Overflow ·

I wish to create a class which extends EventTarget, allowing addEventListener() and dispatchEvent() to be invoked on it. Logically, my class wants to be a singleton; if a page accidentally instantiated more than one, its functionality would break. For this reason, I've implemented the entirety of this class's logic as static fields and methods. Unfortunately extends doesn’t seem to mesh neatly with static, so this doesn’t work: class MyClass extends EventTarget { static dispatch(type) { MyClass.dispatchEvent(new Event(type)); } } MyClass.dispatch('hello'); Uncaught TypeError: MyClass.dispatchE

Comments

Sign in or sign up to comment and upvote.

No comments yet.