A way to construct Functions with custom scopes?
Steve Fink
sphink at gmail.com
Thu Jun 11 00:40:52 UTC 2020
On 6/10/20 11:06 AM, #!/JoePea wrote:
> For example, what if we could write something like
>
> ```js
> function foo() {
> var x = 10
> }
>
> const [scope, returnValue] = scope from foo()
>
> // can't do anything with `scope` directly, it's like an empty object
> (an exotic object?).
> console.log(getOwnAndInheritedKeys(scope)) // empty array
>
> new Function('console.log(x)', { scope }) // logs 10
> ```
-1 from me. I think it would be disastrous for performance. It prevents
any escape analysis and resulting optimizations. It prevents constant
propagation. It might even interfere with inlining. It would add more
points where JITs might need to invalidate their compiled code. In
general, it eliminates much of the remaining freedom that JS engines
have to optimize in the face of the wildly dynamic nature of JavaScript
code.
I didn't understand your use case with Element attributes.
Also, how do you specify which scope you want?
```js
function foo() {
// Scope 1, with y
let x = 1;
// Scope 2, with x and y
var y = 2;
// Scope 3
if (...) {
let z = 3; // Scope 4, with x, y, and z
}
}
```
etc. And with default parameters and things, there are a lot of scopes
to choose from. I won't even explore the messiness of temporal dead zones.
To make it at all practical, I think you'd need to somehow statically
declare which functions to permit this for. But at that point, you're
better off creating and storing a closure at the exact points where you
want to capture scopes (which fixes the "which scope" problem as well.)
And it sounds like that wouldn't work for what you want.
More information about the es-discuss
mailing list