A couple of projects I’ve been working on, required me to turn strings into functions (templating, custom require, mocha clone) and it didn’t seem like there was a good way to do it with things I needed in scope.
The issue with this way is that this doesn’t scale, since you have to keep adding more params of things you need scope for. For example if we wanted to add helper functions:
varcode='log(this); hey(this.the)';varctx={the:'context'};varparams=['log','hey'];// [].toString joins on comma by default so it just worksvarapplies=[function(str){console.log(str)},alert];varfn=(newFunction('return function('+params+') {'+code+'}'))().apply(ctx,applies);
And if you wanted to curry it just wrap it in another function:
12345
varcode='log(this); hey(this.the)';varctx={the:'context'};varparams=['log','hey'];// [].toString joins on comma by default so it just worksvarapplies=[function(str){console.log(str)},alert];varfn=(newFunction('return function('+params+') {return function(){'+code+'}.bind(this)}'))().apply(ctx,applies);
I didn’t really run any benchmarks but I suspect that this is pretty performant and once you wrap your head around it, is actually pretty simple.