Home > Web Front-end > JS Tutorial > body text

A brief discussion on the differences in JS function definition methods

高洛峰
Release: 2016-12-08 13:53:46
Original
1199 people have browsed it

There are two ways to define functions in JS:

(1) Typical function declaration

function slide(arguments){
//...code
}
Copy after login

(2) Define functions in the form of function expressions

var slide = function(arguments){
//...code
}
Copy after login

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(){},有函数名
Copy after login

If it is defined by a function expression

var factorial = function(num){
//...code
}
//...code
console.log(anotherFactorial);//输出function(){},匿名函数
Copy after login


Related labels:
js
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!