Home > Article > Web Front-end > A brief discussion on the differences in JS function definition methods
There are two ways to define functions in JS:
(1) Typical function declaration
function slide(arguments){ //...code }
(2) Define functions in the form of function expressions
var slide = function(arguments){ //...code }
Although the above two The methods are logically equivalent, but there are still some small differences:
Difference 1: The function in Example 1 will be loaded into the scope before the code is executed, while in Example 2 it will be loaded into the scope when the code is executed to that line. There will be a definition;
Difference 2: The function declaration will assign a name to the function, while the function expression creates an anonymous function and then assigns the anonymous function to a variable;
Look at the following example:
function factorial(num){ if(num<=1){ return 1; } else { return num*arguments.callee(num-1); } } var anotherFactorial = factorial; factorial = null; console.log(anotherFactorial);//输出factorial(){},有函数名
If it is defined by a function expression
var factorial = function(num){ //...code } //...code console.log(anotherFactorial);//输出function(){},匿名函数