为什么函数声明在不同的浏览器中处理方式不同? [英] Why are function declarations handled differently in different browsers?
问题描述
f();
函数f(){}
但是,我注意到chrome和firefox对全球职能宣言的不同解释。特别是,chrome很高兴阅读第一遍中的if块内的函数声明,但firefox不是。
尝试{document.write(f);} //在铬中工作
catch(e){document.write(e.message);} //在firefox中引发错误
尝试{document.write(g);} //在chrome和firefox中工作
catch(e){document.write(e.message);}
if(true)function f ){}
函数g(){}
小提琴。我使用的是Chrome 16.0.912.75和Firefox 9.0.1。
这个行为的ECMA标准是什么?是否有一个术语解除其他代码上面的函数声明?是什么代码被解除了解释(都是浏览器的权利)?或者它是其中的一个bug?
函数声明在块中不是有效的。你有未定义的行为 是未定义的。
函数声明在顶层(函数内的全局或顶层)被提升。 / b>
块中的函数声明在严格模式下是一个语法错误
(){
use strict;
if(true){
function g(){}
}
})();
SyntaxError:在严格模式代码中,函数只能在顶层声明或立即在另一个函数内。
Although I couldn't find a reference to this easily in google, I'm familiar with the fact that, in javascript, global function declarations get interpreted before any code is executed. In other words, this works fine:
f();
function f() {}
However, I've noticed that chrome and firefox have different interpretations of what a global function declaration is. In particular, chrome is happy reading a function declaration that is inside an if block in the first pass, but firefox is not.
try {document.write(f);} // works in chrome
catch(e) {document.write(e.message);} // throws an error in firefox
try {document.write(g);} // works in chrome and firefox
catch(e) {document.write(e.message);}
if(true) function f() {}
function g() {}
You can try this example yourself with this fiddle. I'm using Chrome 16.0.912.75 and Firefox 9.0.1.
What is the ECMA standard for this behavior? Is there a term for this process of "lifting" function declarations above other code? Is what code gets "lifted" open to interpretation (are both browsers right)? Or is it a bug in one of them?
Function declarations are not valid in blocks. You have undefined behaviour which is undefined.
Function declarations at a top level (either global or top level within a function) are hoisted.
Function declarations inside blocks are a syntax error in strict mode
(function () {
"use strict";
if (true) {
function g() { }
}
})();
SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.
这篇关于为什么函数声明在不同的浏览器中处理方式不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!