Reputation: 13
Recently I read about the ES5 Specification, there's one confusion in Chapter-10 which is about Execution Context. More exactly, the confusion exists in 10.5[ https://ecma-international.org/ecma-262/5.1/#sec-10.5 ].
The clause 10.5 named Declaration Binding Instantiation, it explains how the component VariableEnvironment of Execution Context is generated.Where Im confused is the item-5-iii: " If existingProp .[[Configurable]] is true... ".
What's the purpose for this, why the PropertyDescriptor.[[Value]] is undefined when call [[DefineOwnProperty]] of global object, and how to prove this step with real javascript code?
Or maybe this is a mistake? Here the [[Value]] should be the declared function object?
Upvotes: 1
Views: 65
Reputation: 371019
When a function is declared on the top level, it checks to see if the property name exists on the global object first. If the property does not exist, then:
c. Let funcAlreadyDeclared be the result of calling env’s HasBinding concrete method passing fn as the argument.
d. If funcAlreadyDeclared is false, call env’s CreateMutableBinding concrete method passing fn and configurableBindings as the arguments.
Otherwise, it goes into the e.
part that you're looking at:
e. Else if env is the environment record component of the global environment then: ...
So, anywhere inside that e.
, funcAlreadyDeclared
will necessarily be true
- the property is already defined, and what remains is to check to see if the property is changeable. The PropertyDescriptor.[[Value]]
will necessarily return a full property descriptor, because inside e.
, we know that the property does exist; that block only runs if funcAlreadyDeclared
is true
.
On the top level, it checks if the property is configurable, and if so, sets the associated property on the global object. Eg, function foo(){}
on the top level will result in window.foo
being defined, and this section checks that window.foo
can be defined.
Having configurable
of true
means:
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
For example, window.top
is not configurable, so the [[DefineOwnProperty]]
will not run:
console.log(Object.getOwnPropertyDescriptor(window, 'top'));
So, trying to declare a function named top
on the top level will throw an error:
function top() {
}
Upvotes: 2