By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,813 Members | 1,257 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,813 IT Pros & Developers. It's quick & easy.

Function Declaration

P: n/a
What is the difference between:

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

and

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

Are there any advantages to doing one over the other?

Dec 13 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
INeedADip wrote:
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
Dec 13 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.