Created
January 26, 2024 21:04
-
-
Save ahrjarrett/45ff8fa443a55f8b03728a7e016787da to your computer and use it in GitHub Desktop.
js function that binds a class's `new` method to the class itself (so you don't need to use `new`)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const bindConstructor = (f) => { | |
| const f_ = f | |
| return function (...args) { | |
| if (new.target !== f_) { | |
| return new f_(...args) | |
| } | |
| } | |
| } | |
| const effect = () => console.log("instantiated another one...") | |
| const myclass = bindConstructor( | |
| class { constructor() { effect() } } | |
| ) | |
| new myclass() | |
| // => instantiated another one | |
| myclass() | |
| // => instantiated another one |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment