Skip to content

Instantly share code, notes, and snippets.

@hikariyo
Created December 10, 2022 12:12
Show Gist options
  • Save hikariyo/d8ee700982a1b421c68eee14e2bc1a9e to your computer and use it in GitHub Desktop.
Save hikariyo/d8ee700982a1b421c68eee14e2bc1a9e to your computer and use it in GitHub Desktop.
Make functions only being able to called once in JavaScript
const obj = {
hello() {
console.log('Hello from obj')
this.hello = () => {}
}
}
obj.hello()
obj.hello()
function once(f) {
let called = false
function apply(target, thisArg, args) {
if (called) {
return
}
called = true
return Reflect.apply(target, thisArg, args)
}
return new Proxy(f, { apply })
}
const foo = once(() => {
console.log('Hello from foo')
})
foo()
foo()
foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment