Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active July 28, 2023 12:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save softwarespot/76252a838efdcace2df1f9c724e37351 to your computer and use it in GitHub Desktop.
Save softwarespot/76252a838efdcace2df1f9c724e37351 to your computer and use it in GitHub Desktop.
Pass context to eval()
function evaluate(code, args = {}) {
// Call is used to define where "this" within the evaluated code should reference.
// eval does not accept the likes of eval.call(...) or eval.apply(...) and cannot
// be an arrow function
return function evaluateEval() {
// Create an args definition list e.g. "arg1 = this.arg1, arg2 = this.arg2"
const argsStr = Object.keys(args)
.map(key => `${key} = this.${key}`)
.join(',');
const argsDef = argsStr ? `let ${argsStr};` : '';
return eval(`${argsDef}${code}`);
}.call(args);
}
const utils = {
print(...args) {
console.log(...args);
}
};
evaluate('utils.print(2 + 3);', {
utils
});
@DerGoogler
Copy link

Does it have contxt break out??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment