Last active
March 29, 2024 06:40
-
-
Save ryanmorr/3b354968bc8c99308295b6f7b035eb67 to your computer and use it in GitHub Desktop.
Emulate the with statement
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
function scope(obj, callback) { | |
const source = callback.toString(); | |
const vars = Object.getOwnPropertyNames(obj).map((key) => `${key} = this['${key}']`); | |
const body = source.substring(source.indexOf('{') + 1, source.lastIndexOf('}')); | |
const fn = new Function(`var ${vars.join(',')}; ${body}`); | |
fn.call(obj); | |
} | |
// Usage: | |
const obj = { | |
foo: 1, | |
bar: 2, | |
baz: 3 | |
}; | |
scope(obj, () => { | |
console.log(foo + bar + baz); //=> 6 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment