为什么不同浏览器对函数声明的处理方式不同? [英] Why are function declarations handled differently in different browsers?

查看:31
本文介绍了为什么不同浏览器对函数声明的处理方式不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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() {}

但是,我注意到 chrome 和 firefox 对全局函数声明有不同的解释.特别是,chrome 很高兴在第一遍读取 if 块内的函数声明,但 firefox 不是.

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() {}

您可以使用这个 fiddle 自己尝试这个例子.我使用的是 Chrome 16.0.912.75 和 Firefox 9.0.1.

You can try this example yourself with this fiddle. I'm using Chrome 16.0.912.75 and Firefox 9.0.1.

这种行为的 ECMA 标准是什么?在其他代码之上提升"函数声明的过程是否有术语?哪些代码被解除"以供解释(两个浏览器都正确)?或者它是其中一个的错误?

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:在严格模式代码中,函数只能在顶层声明或直接在另一个函数中声明.

这篇关于为什么不同浏览器对函数声明的处理方式不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆