Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@chrispsn
Last active October 21, 2019 21:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrispsn/1b536c53a3b9dfdf50ead497faa97000 to your computer and use it in GitHub Desktop.
Save chrispsn/1b536c53a3b9dfdf50ead497faa97000 to your computer and use it in GitHub Desktop.
IE11-compatible version of Brian Beck's eval-in-context
// https://twitter.com/ua6oxa/status/1170457046153650176
"use strict";
function evalInContext(env, code) {
const
s = JSON.stringify,
locals = Object.keys(env),
keys = locals.map(function(k){return s(k)}),
values = locals.map(function(k){return env[k]}),
body = s("return eval(" + code + ")")
return eval("new Function("+keys+","+body+")").apply(this, values)
}
console.assert(3==evalInContext({a: 1, b: 2}, "a + b"))
try {console.log(a)}
catch(e) {console.log("Success! No pollution of namespace")}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment