Created
July 12, 2024 06:20
-
-
Save huynhducduy/029d83e6bbdd9b9641ace0c1ed99745e to your computer and use it in GitHub Desktop.
Wrap a function in `isolate` to prevent it from create closure.
This file contains 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
export default function isolate<T extends (...args: unknown[]) => unknown>(fn: T): T { | |
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- workaround | |
return new Function(` | |
with (new Proxy({}, { | |
has () { return true; }, | |
get (target, property) { | |
if (typeof property !== 'string') return target[property]; | |
throw new ReferenceError(property + ' accessed from isolated scope'); | |
}, | |
set (target, property) { | |
throw new ReferenceError(property + ' accessed from isolated scope'); | |
} | |
})) return ${Function.prototype.toString.call(fn)} | |
`).call( | |
new Proxy( | |
function () { | |
/* do nothing */ | |
}, | |
new Proxy( | |
{}, | |
{ | |
get() { | |
throw new ReferenceError('this accessed from isolated scope') | |
}, | |
}, | |
), | |
), | |
) as T | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment