Skip to content

Instantly share code, notes, and snippets.

@wenbing
Created November 7, 2014 03:15
Show Gist options
  • Save wenbing/7a8fb1729bb734202614 to your computer and use it in GitHub Desktop.
Save wenbing/7a8fb1729bb734202614 to your computer and use it in GitHub Desktop.
function eval(str, context, expose) {
var exposeKeys = [];
var exposeValues = [];
var i;
for (i in expose) {
if (Object.hasOwnProperty.call(expose, i)) {
exposeKeys.push(i);
exposeValues.push(expose[i]);
}
}
return (new Function(
'return function(' + exposeKeys + ') { return function() { ' + str + ' }.bind(this) }'
))().apply(context, exposeValues);
}
var ctx = {};
var expose = {
up: function(str) {
return str.toUpperCase();
}
};
var f = eval('console.log(this, arguments); return up("aaa")', ctx, expose);
console.log(f.toString());
var t = f('Look! Even has args!');
console.log(t);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment