Identifiers - matianfu/redbank GitHub Wiki
Javascript allows the same name for arguments, variables and function declaration. The following code are perfectly valid.
var x = function(x) {
function x() {
x = 20;
}
var x;
return x;
}
var b = x(20); // b is a function now
The criteria is here:
-
in compile time, the arguments add identifier names into scope first. Then variable declarator and function declaration add identifier names second. If the same name already exists, it's OK.
-
in runtime, before the function running, arguments are assigned first by the caller, then if there are any function declarations, the corresponding function objects are created and assigned to the arguments or variables with the same name. Finally, all unassigned arguments and variables are assigned to undefined.
So at compile time:
- First, establish argument name list
- Then check all variable declarator and function declaration, if the name doesn't exist in arguments, create one in local (variable) list; if the name exists, don't create new one in locals.
- Check all identifiers, except in MemberExpression as property or in Property as key. These identifiers are not resolved to local scope names.
- Try to resolve those names in all ancestors, that is, in lexical scope, if it could be resolved, put them into lexical variable list
- Finally, the remaining unresolved identifiers should be considered to be look up in global scope. The global scope is dynamic at run time. So leave them to be resolved at run time.