简体   繁体   English

为什么 function 声明在不同浏览器中的处理方式不同?

[英]Why are function declarations handled differently in different browsers?

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.虽然我无法在 google 中轻松找到对此的引用,但我熟悉这样一个事实,即在 javascript 中,全局 function 声明在执行任何代码之前都会被解释。 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.但是,我注意到 chrome 和 firefox 对全局 function 声明的含义有不同的解释。 In particular, chrome is happy reading a function declaration that is inside an if block in the first pass, but firefox is not.特别是,chrome 很高兴在第一遍中读取位于 if 块内的 function 声明,但 firefox 不是。

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 .你可以用这个fiddle自己试试这个例子。 I'm using Chrome 16.0.912.75 and Firefox 9.0.1.我正在使用 Chrome 16.0.912.75 和 Firefox 9.0.1。

What is the ECMA standard for this behavior?这种行为的 ECMA 标准是什么? Is there a term for this process of "lifting" function declarations above other code?在其他代码上方“提升” function 声明的过程是否有术语? 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.

The ECMA standard for this behavior is to throw a SyntaxError when parsing the script. 此行为的ECMA标准是在解析脚本时抛出SyntaxError。 Unfortunately doing that is not compatible with the web as Raynos says. 不幸的是,正如Raynos所说,这与网络不兼容。

See Which JS function-declaration syntax is correct according to the standard? 根据标准哪个JS函数声明语法是正确的? for some extended discussion on the issue. 关于这个问题的一些扩展讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM