Javascript函数声明之间的区别 [英] Difference between Javascript function declarations
问题描述
以下两个示例有什么区别?
What is the difference between the following two examples?
setInterval(myFunc, 100);
function myFunc() { alert('asdf'); }
setInterval(myFunc, 100);
var myFunc = function myFunc() { alert('asdf'); }
推荐答案
根据ECMA标准,第一个例子是函数语句,而第二个是函数表达式。根据Javascript,函数语句计为定义,这意味着在第一个示例中,它通过整个函数(或脚本,如果它不在函数中)可见。但在第二个例子中, var myFunc在第二行之前不会有 function myFunc的值,因此将传递setInterval undefined
。
According to ECMA standard, the first example is a function statement while the second is a function expression. According to Javascript a function statement counts as a definition, which means in the first example it is visible through the entire function (or script if it's not in a function). But in the second example, var myFunc will not have the value of function myFunc until the second line, and therefore setInterval will be passed undefined
.
函数语句和表达式之间唯一的语法区别是语句不包含在更大的表达式中:例如:( function foo(){})
是一个表达式,而 function foo(){}
是一个语句。
The only syntax difference between function statements and expressions is that statements are not included in are larger expression: eg: (function foo() {})
is an expression, while function foo() {}
is a statement.
注意:我认为旧IE(前9?)将所有函数表达式视为定义。
NB: I believe old IE (pre 9?) treated all function expressions as definitions.
要阐述此答案,请考虑以下代码:
To expound on this answer, consider the following code:
<script language="javascript">
alert(A);
alert(B);
function A() {return "A value";}
var B = function B(){ return "B value";}
alert(A);
alert(B);
</script>
这将提醒(按顺序):
- 功能A()...
- undefined
- 功能A()......
- 功能B()......
- Function A()...
- undefined
- Function A()...
- Function B()...
这篇关于Javascript函数声明之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!