Skip to content

Instantly share code, notes, and snippets.

@ahrjarrett
Created January 26, 2024 21:04
Show Gist options
  • Select an option

  • Save ahrjarrett/45ff8fa443a55f8b03728a7e016787da to your computer and use it in GitHub Desktop.

Select an option

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`)
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