Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bound `this` and closed variables?

Tags:

javascript

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); }
  1. Is it possible to extract that 7 from x?

  2. g closes over x. Is it possible to get array of closed-over variables from g?

like image 426
mpen Avatar asked Jan 05 '23 19:01

mpen


1 Answers

Is it possible to extract that 7 from x?

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 over x. Is it possible to get array of closed-over variables from g?

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).

like image 96
T.J. Crowder Avatar answered Jan 07 '23 17:01

T.J. Crowder