Javascript Function Expressions
Solution 1:
When a function is called as in:
log(greet)
then the identifier log is resolved in the current execution context and, if not found, is searched along the scope chain, ending at the global execution context. If not found, an error is thrown.
In this case, log has been defined using a function declaration so it exists in the global scope so is found. Its value is checked to make sure it's callable (again, if not, an error is thrown) if it is, it's called.
In the call, the identifier greet is resolved and its value passed to the function. If greet can't be resolved (i.e. it doesn't exist on the scope chain), an error is thrown. In this case, it resolves to a reference to the function assigned to greet.
When log is executed, a new execution context is created. The function declaration for log defines a formal parameter a (in its formal parameter list), so a is created as a local variable for log. The values in the call are passed to identifiers in the formal parameter list in order, so the value of greet is assigned to a. Note that initialisation and creation of a new execution context occurs every time a function is called.
The same process is followed when calling:
console.log(a);
so that within console.log, the reference to greet is passed as the first parameter, so it now references the greet function.
The behaviour of console.log is entirely implementation dependent so the internals are unknown, but for functions most tend to just call the function's toString method.
It's a handy feature of ECMAScript that an arguments object is created of the arguments passed to functions, so the values passed are always available as numeric properties of the arguments object if there is no parameter for them to be assigned to. So console.log doesn't have to define any formal parameters, it can just loop over its arguments object and process the passed values in turn.
Post a Comment for "Javascript Function Expressions"