简体   繁体   中英

Function declaration vs function expression causing different results

In this code snippet, trueFactorial(5) returns 120:

 function factorial(num) { if (num <= 1) { return 1; } else { return num * arguments.callee(num - 1); } } var trueFactorial = factorial; var factorial = function(num) { return 0; } console.log(trueFactorial(5)); 

But in this code snippet, trueFactorial(5) returns 0 .

 function factorial(num) { if (num <= 1) { return 1; } else { return num * arguments.callee(num - 1); } } var trueFactorial = factorial; function factorial(num) { return 0; } console.log(trueFactorial(5)); 

The only difference is that we declared factorial through variable assignment in the first snippet. What is the reason for this difference?

Function declarations are hoisted. Variable assignments are not.

In example one, you assign the first function to trueFactorial .

In example two, the second function is hoisted so it gets assigned to trueFactorial .

The JavaScript interpreter first looks at the declaration of all functions in your code with the function <...> (<arguments>) syntax. In your second snippet, you declare the function both time with this syntax, so the interpreter starts by seeing the first declaration, memorize its content, and then see another declaration. At this point, it will replace the first declaration by the new one.

When you use the var keyword, the declaration is not seen by the interpreter before the start, but while the code is running.

In the second example your function is hoisted and gets assigned to trueFactorial function. Meaning it is in the end a reference to the same function. In the first example the reference points to another address in memory.

See:

 function factorial(num){ if (num <=1){ return 1; } else { return num*arguments.callee(num-1); } } var trueFactorial = factorial; var factorial = function(num){ return 0; } console.log(trueFactorial(5));//120 console.log(trueFactorial === factorial);//false 

 function factorial(num){ if (num <=1){ return 1; } else { return num*arguments.callee(num-1); } } var trueFactorial = factorial; function factorial(num){ return 0; } console.log(trueFactorial(5));//0 console.log(trueFactorial === factorial);//true 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM