Is it possible to get whatever's bound to this
and all the closed-over variables out of a function?
e.g.
function f() { console.log(this); }
let x = f.bind(7);
function g() { console.log(x); }
Is it possible to extract that 7
from x
?
g
closes over x
. Is it possible to get array of closed-over variables from g
?
Is it possible to extract that
7
fromx
?
Nope. f
would have to explicitly give you a way to retrieve this
(for instance, function f() { return this; }
). Since it doesn't, you can't.
In specification terms, you're asking if it's possible to retrieve the value of the [[BoundThis]] internal slot from a function. [[BoundThis]] only appears three times in the spec: Where bound function exotic objects are described, where their [[Call]] internal operation is described, and where the process of creating them is outlined. So, not in an operation allowing you to retrieve the value.
g
closes overx
. Is it possible to get array of closed-over variables fromg
?
Nope. :-) Which is a good thing in terms of having private information and a public API to it.
Providing that would require a means of accessing the list of bindings in the lexical environment object attached to g
and all of its outer lexical environments. There's none in the specification.
There's no specification reason either or both couldn't be added, but I think (and this is just my personal speculation) that TC39 (the committee that decides these things) would be a hard sell on the first and a nearly impossible sell on the second (which has massive, and negative, implementation impacts).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With