-
-
Save bingzer/3391a38c4f4b7d6689ce42b474b54625 to your computer and use it in GitHub Desktop.
Pass context to eval()
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 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 | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment