Last active
December 16, 2015 04:49
-
-
Save kybernetikos/5380463 to your computer and use it in GitHub Desktop.
Define local variables from a map.
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
// 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