Chrome如何管理对javascript构造函数的引用

Seb*_*ien 3 javascript google-chrome

请考虑以下代码:

function A() {
    console.log("first");
}

var f = A;

function A() {
    console.log("second");
}

var g = A;

f();
g();
Run Code Online (Sandbox Code Playgroud)

它在萤火虫中输出"第一","第二",这是我认为它应该做的.
但它在Chrome控制台或firefox中输出"秒","秒",(从文件执行时,而不是在firebug中).
为什么要改变'f'中的参考值?我做第二个"函数A(){"??

看起来好像是吊装是问题(请参阅apsillers的回答).但是,为什么这个例子正常工作(我的意思是输出第一秒):

var A = function A() {
    console.log("first");
}

var f = A;

A = function A() {
    console.log("second");
}

var g = A;

f();
g();
Run Code Online (Sandbox Code Playgroud)

我在第二个函数声明中使用"A = ..."的事实阻止了这个函数的提升?

aps*_*ers 7

函数声明被提升到其作用域的顶部,因此您的代码将被解释为:

function A() {
    console.log("first");
}

// overwrite previous A
function A() {
    console.log("second");
}

// variable declarations are hoisted as well
// (not directly related to your problem here, but worth noting)
var f;
var g;

f = A;
g = A;

f();
g();
Run Code Online (Sandbox Code Playgroud)

其产生的输出second,second在任何现代浏览器.

在你的第二个例子中,var A = ...你现在使用的是函数表达式,而不是函数声明.函数表达式不会被挂起.

萤火虫古怪

似乎 - 由于某种原因 - Firebug没有正确执行功能声明吊装:

console.log(bar);  // this line incorrectly produces a ReferenceError!

function bar() { }
Run Code Online (Sandbox Code Playgroud)

此代码段应该记录function bar() { }.它在任何适当的浏览器环境中都这样做,但不是Firebug.

编辑:

Firebug行为的原因是Firebug代码在块内部运行,并且函数声明在块中无效.但是,浏览器仍然会以非严格模式处理它们,但它们如何处理它们会有所不同.Firefox将它们视为无线(而IE和Chrome确实提升它们,因为它发生).