-
-
Save hikariyo/d8ee700982a1b421c68eee14e2bc1a9e to your computer and use it in GitHub Desktop.
Make functions only being able to called once in JavaScript
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 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