- use function statement,
- use function expression
Function statement:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function foo() { | |
alert("foo"); | |
} |
Function expression:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var foo = function() { | |
alert("foo"); | |
}; |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//call before function foo is defined | |
foo(); //=> alert("foo"); | |
function foo() { | |
alert("foo"); | |
} | |
//call after function foo is defined | |
foo(); //=> alert("foo"); |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//call before function foo is defined | |
foo(); // will fail, because foo() is not defined. | |
var foo = function () { | |
alert("foo"); | |
} | |
//call after function foo is defined | |
foo(); //=> alert("foo"); |
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.