There are two ways to define a function in JavaScript, one is a function declaration and the other is a function expression. There are a few subtle differences between the two ways of defining.
1. function declaration:
function keyword + function name + function Body constitute a functional declaration, the following form:
function functionname (arg0, arg1, arg2) {//function body}
Firefox, Safari, Chrome, and Opera all define a nonstandard Name property for the function , which gives you access to the name specified by the function:
alert (functionname.name);//"functionname"
an important feature of function declarations is the promotion of function declarations ( function declaration Hoisting ) , which means that the function declaration is read before the code executes, that is, the function can be called before the function declaration:
SayHello ();//"Hello" function SayHello () {alert ("hello~");}
2. function Expressions:
a function expression is a bit like a regular variable assignment statement, in which case the function created is called an anonymous function . (anonymous function) , the specific form is as follows:
var functionname = function (arg0, arg1, arg2) {//function body};
a function expression differs from a function declaration in a two-point way because the function expression is defined as an anonymous function, so the Name property of the variable is an empty string:
alert (functionname.name);//""
The second is that the function expression does not have a function declaration promotion, so the function cannot be called before the function expression:
SayHello ();//errorvar SayHello = function () {alert ("ello~");};
Look at an example that helps us to better understand the function declaration function expression:
Code Snippet One:
if (condition) {function SayHello () {alert ("Hello version_1"); }} else {function SayHello () {alert ("Hello version_2"); }}
on the surface, the above code indicates that when condition is true , a definition of SayHello () is used , otherwise another definition is used. However, this approach is dangerous and may have unintended consequences, but if you use a function expression, there is no problem with the following code snippet:
Code fragment Two:
var sayhello;if (condition) {SayHello = function () {alert ("Hello version_1"); };} else {SayHello = function () {alert ("Hello version_2"); };}
This article is from the "barrel of fake dog excrement" blog, please be sure to keep this source http://xitongjiagoushi.blog.51cto.com/9975742/1637798
function declarations and function expressions in JavaScript