Home >Web Front-end >JS Tutorial >Introduction to the differences in how JS functions are defined_Basic knowledge

Introduction to the differences in how JS functions are defined_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:08:261328browse

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 methods are logically equivalent, 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 not be defined until the code is executed to that line;
Difference 2: The function declaration assigns 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 example below:

function factorial(num){
if(num<=1){
return 1;
}
else {
return num*arguments.callee(num-1);
}
}
var anotherFactorial = factorial;
factorial = null;
console.log(anotherFactorial);//输出factorial(){},有函数名
若是以函数表达式定义
var factorial = function(num){
//...code
}
//...code
console.log(anotherFactorial);//输出function(){},匿名函数

The above introduction to the differences in JS function definition methods is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home more.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn