On 13/10/2005 21:17, Jim Moon wrote:
I'm curious about this syntax:
<variable>=function(){...}
What you have there is a function expression.
Function declarations:
function identifier() {
}
are parsed into function objects before execution begins[1]. This is why
one can call a declared function before its definition in the source.
myFunction(); /* No problem calling this here */
function myFunction() {
/* ... */
}
Function expressions are different in that they only create function
objects /if/ they are evaluated. This means that control structures can
prevent them from being created at all, or repeatedly evaluate the
expression to create several distinct function objects from the same code.
var myFunction;
if(false) {
myFunction = function() { /* ... */ };
}
Here, a function object won't be created because the code branch
containing the function expression will never be entered.
This feature affords tremendous flexibility to the author.
Like function declarations, function expressions can be given identifiers.
var myVariable = function myFunction() {};
However, the identifier is only for use within the function itself; it
allows the function to refer to itself.
[snip]
Mike
[1] To be more precise, function declarations are parsed when
their containing execution context is entered. That is,
global function declarations are parsed immediately, but
inner functions are only parsed when their outer function is
called. Moreover, they are reparsed on each invocation of
that outer function.
function myGlobalFunction() {
function myInnerFunction() {
/* ... */
}
/* ... */
}
When interpreted, the function, myGlobalFunction, will be
created immediately. However, the function, myInnerFunction,
will not exist yet.
When the outer function is called, the inner function will
then be created before statements within myGlobalFunction are
executed. When the scope of myGlobalFunction is left, the
inner function will be destroyed.
Incidentally, variable declarations work much the same way.
Declared variables within a particular execution context are
created before any code is executed. If an initialisation is
included with the declaration
var myVariable = ...;
the variable will exist from the start, but actual
assignment will not occur until that point in the code is
reached and evaluated.
--
Michael Winter
Prefix subject with [News] before replying by e-mail.