Skip to content

Instantly share code, notes, and snippets.

@kybernetikos
Last active December 16, 2015 04:49
Show Gist options
  • Save kybernetikos/5380463 to your computer and use it in GitHub Desktop.
Save kybernetikos/5380463 to your computer and use it in GitHub Desktop.
Define local variables from a map.
// Bad behaviour ahead!
// doesn't work with strict mode.
function local(obj) {
var global = Function("return this")();
var tmpName = "_tmp";
while (tmpName in global) {
tmpName = "_"+tmpName;
}
global[tmpName] = obj;
var defineString = "var "+Object.keys(obj).join(", ")+";\n";
defineString +="(function() {\n\tvar global = Function('return this')();\n\t";
for (var key in obj) {
defineString += "\t" + key +" = global."+tmpName+"['" + key + "'];\n"
}
defineString += "\tdelete global['"+tmpName+"']\n})();\n"
return defineString;
}
// example:
function bob() {
eval(local({
a: 23,
b: 40
}));
return a * b;
}
console.log(bob());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment