Define a scope for javascript Function constructor

2019-08-01 12:42发布

问题:

I'm trying to create some dynamic functions that require an enclosing scope. Currently this works:

eval("with (scope) (function () {return scope.prop})")

This approach seems a bit hacky. User supplied code is nowhere near this so I'm not worried about security, it's just that it seems like there should be a better way.

I know the Function constructor does not include anything apart from the global scope, but I was hoping there was some way to 'inject' scope into the Function constructor. Not call or apply or bind, but construct a function with a defined scope.

Is it possible to define a scope when using the Function constructor? Is it something that may be included in the standard in the future?