Saturday, October 22, 2011

The function definition in Javascript

I highly recommended Douglas Crockford's book "Javascript:The good parts". In the page 133 of the book, the author mentioned 2 ways of defining a function:
  • use function statement,
  • use function expression
Their results are exactly the same. For example,
Function statement:

Function expression:

The above two have the exactly same result. they will both define a function foo. But I found there are still one difference: scope.
The function statement is globally scoped, it can be put anywhere in the javascript, and you can call the function before or after it is defined.
For example:

But in function expression is different, the function call statement must be after the function is defined, otherwise the function call will be failed.
For example:

When you think a little deeper, the error of function expression make sense, because the function expression means first declare a variable, then assign it with a function object. Why it failed before the function defined is because the variable is not declared and assigned yet.

So if you use the function expression to define a javascript function, you need to aware this issue.

0 comments:

Post a Comment