哪个JS函数声明语法按照标准是正确的? [英] Which JS function-declaration syntax is correct according to the standard?

查看:133
本文介绍了哪个JS函数声明语法按照标准是正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var foo = function(){return 1; }; 
if(true){
function foo(){return 2; }
}
foo(); // 1在Chrome中// 2在FF
//我只是想确定,在这种情况下FF 4是不是标准?

编辑:

如果我们有这个:

  var foo = function(){return 1; }; 
if(true)function foo(){return 2; }
foo(); //是1标准还是2标准?


解决方案

原始海报的代码不被ECMAScript标准。 (由于法律原因,ECMAScript是JavaScript语言规范的正式名称)。然而,这是一种语言的常见扩展,不幸的是,在不同的浏览器中执行的语言不同。

在标准JavaScript中,函数定义只能出现在顶层代码中,或者出现在函数主体的顶层。你不能在封闭函数体和函数定义之间有条件句,循环语句,甚至花括号。



例如,这是允许的:

 函数f(){
函数g(){
...
}
}

但这不是:

<$ p (







$ b $

使图片复杂化的是,大多数浏览器都接受后面的代码,但是每一个都赋予它自己的特质解释。 Firefox会像这样对待它:



pre $ $
$ g $ g $ {
...
}
}
}



< ECMAScript委员会正在考虑为这些函数声明(而不是函数定义)选择一个特定的解释。他们还没有做出决定。 Mozilla正在讨论其首选解决方案此处


  var foo = function(){ return 1; };
  if (true) {
    function foo(){ return 2; }
  }
  foo(); // 1 in Chrome // 2 in FF
  //I just want to be sure, is FF 4 not "standard" in this case?

Edit:

what if we have this:

  var foo = function(){ return 1; };
  if (true) function foo(){ return 2; }      
  foo(); // is 1 standard or is 2 standard?

解决方案

The original poster's code isn't permitted by the ECMAScript standard. (ECMAScript the official name for the JavaScript language specification, for legal reasons.) It is, however, a common extension to the language—one which is, unfortunately, implemented differently in different browsers.

In standard JavaScript, function definitions may only occur in top level code, or at the top level of a function's body. You can't have conditionals, loops, or even curly braces between the enclosing function's body and the the function definition.

For example, this is permitted:

  function f() {
    function g() {
      ...
    }
  }

but this is not:

  function f() {
    {
      function g() {
        ...
      }
    }
  }

What complicates the picture is that most browsers do accept this latter code, but each assigns its own idiosyncratic interpretation to it. Firefox treats it like:

  function f() {
    {
      var g = function g() {
        ...
      }
    }
  }

The ECMAScript committee is considering choosing a specific interpretation for these "function statements" (as opposed to function definitions). They haven't made a decision yet. Mozilla is discussing its preferred solution here.

这篇关于哪个JS函数声明语法按照标准是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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