Reputation: 3930
I am reading "JavaScript: The Definitive Guide, 6th edition", and in section "3.10.3 The Scope Chain" (page 55) it states -
"If we think of local variables as properties of some kind of implementation-defined object, then there is another way to think about variable scope."
Can someone explain what is meant by "implementation-defined object"?
Upvotes: 2
Views: 128
Reputation: 71908
Think of an abstract object that is not exposed to us. It's defined by the implementation, and available to the implementation only – "implementation" meaning the JavaScript engine which will be running your code.
For example, consider the following function:
function f(a,b) {
var foo = 5;
return a + b + foo;
}
The variables and arguments defined within that function's scope could be represented as an object that would look like this:
{
a,
b,
foo
}
The values of the object's properties can change during the execution of the function. If you call the function with f(1,2)
, for example, the object will look like this as soon as the function execution starts:
{
a: 1,
b: 2,
foo: undefined
}
After foo
is assigned 5
, it will look like this:
{
a: 1,
b: 2,
foo: 5
}
Consider this object as if it was declared inside the function. So, you can access the values of a
, b
and foo
inside the function, but not outside it.
Upvotes: 3
Reputation: 165961
Local variables are internally represented as bindings to the lexical environment, as shown by the spec (ES5 10.5 - note that "env" in the following quote refers to the lexical environment of the current scope):
For each VariableDeclaration and VariableDeclarationNoIn d in code, in source text order do
Let dn be the Identifier in d.
Let varAlreadyDeclared be the result of calling env’s HasBinding concrete method passing dn as the argument.
If varAlreadyDeclared is false, then
Call env’s CreateMutableBinding concrete method passing dn and configurableBindings as the arguments.
Call env’s SetMutableBinding concrete method passing dn, undefined, and strict as the arguments.
Since you have no programmatic access to the lexical environment of a scope, you can't see these bindings. But it means you can think of local variables as being properties of this invisible object, just as global variables become properties of the global object (which you can access).
This concept is summarised nicely at the start of the section quoted from above:
Every execution context has an associated VariableEnvironment. Variables and functions declared in ECMAScript code evaluated in an execution context are added as bindings in that VariableEnvironment’s Environment Record.
To understand the process in more detail, have a look at the specification of the CreateMutuableBinding
and setMutableBinding
methods.
To answer your actual question, in this case, the "implementation-defined object" is the lexical environment of the current execution context.
Upvotes: 3