How to define a function
There are two ways to define a function expression, one is a function declaration and the other is a function expression .
the way a function is declared, an important feature of the function declaration is the function declaration promotion (Functions declaration hoisting), which means that the function declaration is read before executing the code. This means that the function declaration can be placed after the statement that called it, like this
1 Sayhi ();//Declaration function (Function declaration hoisting)2 function Sayhi () {3 alert ("hi!" ); 4 }
There are several expressions for function expressions , and the following are the most common
var function (AGR1,ARG2) {//Create anonymous function + ' + arg2);//function Body }
function expressions, like other expressions, must be assigned before they are used. For example, the following code will cause an error.
var true ; // never do this! Different browsers will behave differently do not do this! if(condition) { function sayhi () { alert ("hi!" ); } Else { function sayhi () { alert ("yo!" ); } } Sayhi ();
Functions can be assigned to variables and can naturally be returned as return values.
Recursive
Like every language, the idea of any method or function to solve a problem has two basic ideas of recursion and enumeration, but the recursive return in JS has a small trap, which needs attention here. Take a look at the following code, just a simple function of factorial.
// Factorial, it doesn't seem to matter. function factorial (num) { if (Num <= 1 return 1; else { return num * factorial (num-1 var anotherfactorial = Factori Al Factorial = null ; Alert (Anotherfactorial ( 4)); // error!
The hidden problem here is that if you first use a variable anotherfactorial to point to the Factorial function object (oh, function object), and then empty the fatorial (equivalent to the Factorial property =null of the Window object), When you execute anotherfactorial () again, you will find that calling Fatorial
The error occurs because NULL is not a function. So to avoid such problems we can improve this function, using Arguments.callee can solve this problem.
Ss