JS中在if else 中定义 function 的问题


代码如下:


 (function (){
    if(true){
        inner();
        function inner(){
            alert(1);
        }
    }else{ }
})()

在IE8-11、chrome、safari 中均弹出了 alert(1);
但是在firefox 31.0 中 提示了 inner is not defined

但是改成下面这样就可以了:


 (function (){
    if(true){
        function inner(){
            alert(1);
        }
        inner();
    }else{ }
})()

是 SpiderMonkey 的BUG 吗?

再补充一点:


 (function (){
    if(true){
        inner();
    }else{ }
    function inner(){
        alert(1);
    }
})()

这样的话 在所有浏览器下都是正常的,alert(1)了

语法 JavaScript

DannyR 9 years, 7 months ago

google了一下,可以看下stackflow上的答案: 链接描述

想飞and无翼 answered 9 years, 7 months ago

ES5之前JS有一个特性叫做 声明提前 (具体请自行Google),但是在ES6中已经取消了这个"feature"了。所以有可能是Firefox已经开始支持ES6了?

哦噶米丶小红帽 answered 9 years, 7 months ago


 console.log(typeof foo);
function foo(){ return 1; }
console.log(typeof foo);

上面这段代码在各个浏览器中有一样的结果: "function" "function"

这是没有浏览器差异的行为,原因是函数声明提升(Function Declaration Hoisting)。

不明白函数声明提升,或者连函数声明和函数表达式的分别都不太清楚,可以看看汤姆大叔的《 揭秘命名函数表达式 》。

表达式和声明存在着十分微妙的差别。函数声明会在任何表达式被解析和求值之前先被解析和求值,即使你的声明在代码的最后一行,它也会在同作用域内第一个表达式之前被解析/求值。



 console.log(typeof foo);
  if (true) {
    function foo(){ return 1; }
  }
  console.log(typeof foo);

上面这段代码在Gecko引擎中打印 "undefined" "function" ;而在其他浏览器中则打印 "function" "function"

原因在于Gecko 加入了ECMAScript以外的一个feature :条件式函数声明。

Conditionally created functions
Functions can be conditionally declared, that is, a function declaration can be nested within an if statement.

Note: Although this kind of function looks like a function declaration, it is actually an expression (or statement), since it is nested within another statement. See differences between function declarations and function expressions.

注意引用的Note:条件式函数声明跟函数表达式的处理方式一样。因此,条件式函数声明丧失了函数声明提升的特性。


基于以上原因,请不要在你的代码里将函数声明嵌套在条件语句内。

邪èССξ answered 9 years, 7 months ago

Your Answer