用函数语句和表达式定义函数的区别

//函数语句

function test(str)

{

    alert(str);

}

 //表达式定义

var test1 = function(str)

{

    alert(str);

}

 可能大多数人平时都没有注意过,或者根本就没有相关这两种方式有没有什么不同。那么这两种方式有区别吗?<br />

两种方式都创建了新的函数对象, 但函数声明语句的函数名是一个变量名, 变量指向函数对象, 和通过var声明变量一样,

函数定义语句中的函数被显示地提前到了脚本或函数的顶部, 因此它们在整个脚本和函数内都是可见的,但是使用var 表达式定义函数,

只有变量声明提前了,变量初始化代码仍然在原来的位置, 用函数语句创建的函数, 函数名称和函数体均被提前,所以我们可以在声明它之前就使用它。

 1 <!DOCTYPE html>
 2 <html>
 3 <body>
 4 <script>
 5 alert(typeof(test)); // function
 6 test('abc'); // abc
 7 
 8 alert(typeof(test1)); // undefined
 9 
10 if(test1)
11     test1('abc'); // will not execute
12 else
13     alert('test1 is undefined'); // test1 is undefined
14 // 函数语句
15 function test(str)
16 {
17     alert(str);
18 };
19 // 表达式定义
20 var test1=function(str)
21 {
22     alert(str+ ' from test1');
23 };
24 alert(typeof(test1)); // function
25 if(test1)
26     test1('abc'); // abc from test1
27 else
28     alert('test1 is undefined'); // will not execute
29 </script>
30 </body>
31 </html>
原文地址:https://www.cnblogs.com/liwei45212/p/3026359.html