问题描述
在块作用域中定义函数时,我遇到了一个问题.请考虑以下程序:
I just ran into a problem when defining a function in a block scope. Consider the following program:
try {
greet();
function greet() {
alert("Merry Christmas!");
}
} catch (error) {
alert(error);
}
我希望该程序向Merry Christmas!
发出警报.但是在Firefox中,它提供了以下ReferenceError
:
I expected this program to alert Merry Christmas!
. However in Firefox is gives me the following ReferenceError
:
ReferenceError: greet is not defined
在Opera和Chrome浏览器上,它会按我预期的方式警告问候语.
On Opera and Chrome it alerts the greeting as I expected it to.
很明显,Firefox将块作用域内的功能视为FunctionExpression
,而Opera和Chrome将其视为FunctionDeclaration
.
Evidently Firefox treats the function inside the block scope as a FunctionExpression
while Opera and Chrome treat it as a FunctionDeclaration
.
我的问题是,为什么Firefox的行为有所不同?哪个实现更合乎逻辑?哪个符合标准?
My question is why does Firefox behave differently? Which implementation is more logical? Which one is standards compliant?
我了解到JavaScript中的声明是悬挂式的,因此,如果在同一作用域中的两个或多个不同块中声明相同的函数,则会发生名称冲突.
I understand that declarations in JavaScript are hoisted and so if the same function is declared in two or more different blocks in the same scope then there'll be a name conflict.
但是,每次声明函数时都重新声明该函数更合乎逻辑,这样您就可以执行以下操作:
However wouldn't it be more logical to redeclare the function every time it's declared so that you can do something like this:
greet(); // Merry Christmas!
function greet() {
alert("Merry Christmas!");
}
greet(); // Happy New Year!
function greet() {
alert("Happy New Year!");
}
除了解决我上面描述的块作用域问题外,我认为这将非常有用.
I think this would be very useful, in addition to solving the block scoping problem I described above.
推荐答案
实际上,显然不是 标准化了块作用域内的函数声明,并且行为依赖于实现.不同的实现有不同的响应.如果尝试在if语句中声明一个函数,您会感到很奇怪.
Actually, function declarations inside block scopes is expressly not standardized and the behavior is implementation dependent. Different implementation respond differently. You'd get the same weirdness if you tried to declare a function inside an if statement.
ES5规范建议实现者将在块内的函数声明标记为警告或错误.
The ES5 spec recommends that implementers make function declarations inside blocks be marked as a warning or error.
这篇关于函数声明或函数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!