JavaScript中函数表达式与声明的区别
1. 函数声明:
函数声明(或函数语句)定义具有指定参数的函数,而不需要变量赋值。它们独立存在,即它们是独立的构造,不能嵌套在非功能块中。使用 function 关键字声明函数。
语法:
function gfg(parameter1, parameter2) {
 //A set of statements
 }
2. 函数表达式:
函数表达式就像函数声明或函数语句一样工作,唯一的区别是函数名不是在函数表达式中开始的,也就是说,匿名函数是在函数表达式中创建的。函数表达式在定义后立即运行。
语法:
var gfg = function(parameter1, parameter2) {
 //A set of statements
 }
示例1: 使用函数声明
<!DOCTYPE html>
<html>
<head>
    <title>Function Declaration</title>
</head>
<body>
    <center>
        <h1 style="color:green">YiibaiForGeeks</h1>
        <h3>Function Declaration</h3>
        <script>
            function gfg(a, b) {
                return a * b;
            }
            var result = gfg(5, 5);
            document.write(result);
        </script>
    </center>
</body>
</html>
运行结果:
25
示例2: 使用函数声明
<!DOCTYPE html>
<html>
<head>
    <title>Function Expression</title>
</head>
<body>
    <center>
        <h1 style="color:green">YiibaiForGeeks</h1>
        <h3>Function Expression</h3>
        <script>
            var gfg = function(a, b) {
                return a * b;
            }
            document.write(gfg(5, 5));
        </script>
    </center>
</body>
</html>
运行结果:
25
极客教程