Home>Article>Web Front-end> The difference between the two forms of function declaration

The difference between the two forms of function declaration

yulia
yulia Original
2018-09-08 16:49:02 1920browse

We know that the keyword function is used to define functions; function definitions can be written as function definition expressions or in the form of statements. For example, the following two ways of writing

var f = function(x){return x+1;} //将表达式赋值给一个变量 函数表达式 function f(x){return x+1;} //含有变量的语句     函数声明

Although the function declaration statement and the function definition expression contain the same function name; there are still differences between them.
Same points: Both methods create new function objects; both will be "advanced" (functions defined in function statements are displayed to the top of the script or function, so they are visible within the entire script );
Difference: The function name in the function declaration statement is a variable name, and the variable points to the function object. Like declaring variables through var, functions defined in function statements are displayed ahead to the top of the script or function, so they are visible within the entire script;
1. Using var only variables are declared ahead--the initialization of variables However, in the original position, if the function declaration statement is used, the function name and function body are both in advance
Summary: Simply speaking, the function expression method (that is, the var declaration method) can only be called after the var statement is declared; And function declaration (that is, function declaration method) function can be called before function declaration.
These situations are because the function expression is assigned to the variable f during the function running stage; and the function declaration has been assigned to the variable f before the code is run, that is, during the code parsing stage
We can look at the following code :

console.log(f,"函数前") var f = function (x) { return x + 1;//函数表达式 } console.log(f,"函数后")

And the result of running this code:

The difference between the two forms of function declaration##

console.log(f,"函数前") function f(x) { return x + 1;//函数声明 } console.log(f,"函数后")

The result:

The difference between the two forms of function declaration

The above is the detailed content of The difference between the two forms of function declaration. For more information, please follow other related articles on the PHP Chinese website!

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