为什么函数声明在不同的浏览器中处理不同?

Chr*_*ris 4 javascript firefox google-chrome

虽然我在google中找不到对此的引用,但我很熟悉这样一个事实,即在javascript中,全局函数声明在任何代码执行之前都会得到解释.换句话说,这很好用:

f();
function f() {}
Run Code Online (Sandbox Code Playgroud)

但是,我注意到chrome和firefox对全局函数声明的解释有不同的解释.特别是,chrome很高兴在第一遍中读取一个if块内的函数声明,但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() {}
Run Code Online (Sandbox Code Playgroud)

你可以用这个小提琴自己尝试这个例子.我使用的是Chrome 16.0.912.75和Firefox 9.0.1.

这种行为的ECMA标准是什么?这个"提升"函数声明的过程是否有一个术语高于其他代码?什么代码被"解除"对解释是开放的(两种浏览器都是正确的)?或者是其中一个中的错误?

Ray*_*nos 11

函数声明在块中无效.您具有不确定的行为不确定的.

顶层的函数声明(函数中的全局或顶级)被提升.

块内的函数声明在严格模式下是语法错误

(function () { 
  "use strict"; 
  if (true) { 
    function g() { } 
  } 
})();
Run Code Online (Sandbox Code Playgroud)

SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.


归档时间:

查看次数:

5096 次

最近记录:

13 年,8 月 前