Function Declaration

I

INeedADip

What is the difference between:

function setupGrid( param ){......}

and

setupGrid = function( param ){......}

Are there any advantages to doing one over the other?
 
M

Michael Winter

INeedADip said:
What is the difference between:

function setupGrid( param ){......}

and

setupGrid = function( param ){......}

The point at which function object is created. Other aspects of function
object creation, such as the scope chain, remain the same.

The function object that results from evaluating a function declaration
(the first snippet) is created when the enclosing execution context is
entered, but before code is executed. For function declarations in
global scope, this means that the function object is created before
other global code is executed. For declarations nested within other
functions, the function object is created when the enclosing function is
called.

Function expressions (the second snippet) only create function objects
if they are evaluated, and then only at the point of evaluation.

There are some syntactic differences in that function declarations
cannot occur where just any statement may be used. So, for example, a
function declaration cannot exist as the statement (or within a block)
that's expected after an if statement.

if (...) {
function identifier() {} /* Wrong! */
}

Function expressions aren't constrained in this way, which allows
conditional creation of functions:

var identifier;

if (...) {
identifier = function () {}; /* OK */
}

This also means that a function expression can occur within a with
statement, allowing additional objects to be added to the scope chain.

The identifier in function expressions is also different. With a
function declaration, the identifier that follows the keyword, function,
is the name for a variable that refers to the function object. This
identifier is added to the variable declaration of the execution
context: a local variable within functions, and a global variable at
global scope. With function expressions, the optional identifier is not
exposed outside that function:

var identifier = function hidden() {
alert(typeof hidden); /* function */
};

alert(typeof hidden); /* undefined */

It's just a way of referencing the function from within the function
without resorting to the arguments.callee property.
Are there any advantages to doing one over the other?

Not as such: they're usage differs.

Hope that helps,
Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top