Javascript 范围怪异、功能和浏览器

Javascript scope weirdness, function and browser

我认为这样做:

var what = function () {};

还有这个

function what () {}

在 JS 中是一样的,因为函数应该是 "first class object"。

今天我在 Firefox 中了解到这段代码:

var test = true;
if (test) {
    function what () {
      alert("foo");
    }
} else {
    function what () {
      alert("bar");
    }
}
what();

显示 foo,出于奇怪的原因 chrome 显示 bar... 为什么是 [第一]? 这样做:

var test = true, what;

    if (test) {
        what = function() {
          alert("foo");
        }
    } else {
        what = function () {
          alert("bar");
        }
    }
    what();

解决了问题.. 为什么是[第二]? 你可以在这里 http://jsfiddle.net/7cbs5gr7/ 试试

[摘要]我有两个问题:

  1. 为什么 chrome 和 firefox 对此采取不同的方式? -附加一个:哪个是对的? -
  2. 为什么在 var 中显式设置函数可以解决问题?

像这样声明一个函数

what = function () {
    alert("foo");
}

function what () {
    alert("foo");
}

是两个不同的东西。

在第一种情况下,变量被提升并且函数定义需要脚本执行通过 ifelse 中的那个点。在第二种情况下,函数只是被声明并且可以从任何地方访问,而不管 ifelse.

中的条件如何

Functions can be conditionally defined using either //function statements// (an allowed extension to the ECMA-262 Edition 3 standard) or the Function constructor. Please note that such function statements are no longer allowed in ES5 strict. Additionally, this feature does not work consistently cross-browser, so you should not rely on it.

滚动到 Conditionally defining a function