Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active March 29, 2024 06:40
Show Gist options
  • Save ryanmorr/3b354968bc8c99308295b6f7b035eb67 to your computer and use it in GitHub Desktop.
Save ryanmorr/3b354968bc8c99308295b6f7b035eb67 to your computer and use it in GitHub Desktop.
Emulate the with statement
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