Ron Inbar
Ron Inbar

Reputation: 2224

JavaScript lexical environments as objects

I couldn't help noticing the analogy between JS objects and lexical environments (as explained, for example, here). Both are containers of name/value pairs. Both have a link to another thing of the same kind: in the case of lexical environments, the parent environment, and in the case of JS objects, the prototype object. Both kinds of links practically serve the same purpose: in the case of lexical environments, to look up a variable's value in the chain of lexical environments, and in the case of objects, to look up a property's value in the prototype chain.

In view of this close analogy, is there a way to reference a lexical environment as an object from within a JS program? Are there any plans to add such a feature to the language in the future? I'm sure it's useful for something...

Upvotes: 1

Views: 161

Answers (1)

Bergi
Bergi

Reputation: 664766

There is one important distinction where the analogy breaks down: lexical environments are created from static code analysis, and do not change their shape. They are records, not dynamic objects. This both helps the interpreter/compiler to optimise lookups, and prevents them from being exposed as objects.

There are only two little things that introduce dynamic scoping: eval and with. (The latter allows to actually put dynamic objects in the scope chain). They're both despised because of this.

Upvotes: 1

Related Questions