在 JavaScript 中,您可以通过多种不同的方式定义函数:
function BatmanController () {
}
var BatmanController = function () {
}
// If you want to be EVIL
eval("function BatmanController () {}");
// If you are fancy
(function () {
function BatmanController () {
}
}());
我今天偶然遇到了一个意想不到的行为。当声明一个与函数同名的局部变量(以奇特的方式)时,局部变量出现在局部范围内。例如:
(function () {
"use strict";
function BatmanController () {
}
console.log(typeof BatmanController); // outputs "function"
var RobinController = function () {
}
console.log(typeof RobinController); // outputs "function"
var JokerController = 1;
function JokerController () {
}
console.log(typeof JokerController); // outputs "number", Ehm what?
}());
有人知道为什么 var JokerController
没有被 function JokerController
覆盖吗?我在 Chrome、Safari、Canary、Firefox 中对此进行了测试。我猜这是由于在 V8 和 JägerMonkey 引擎中进行了一些“前瞻性”JavaScript 优化。但是是否有任何技术解释来解释这种行为?
最佳答案
因为函数和变量声明被提升到它们出现的范围的顶部,而赋值发生在适当的位置。您的代码被有效地解释为:
(function () {
"use strict";
function BatmanController () {} // Declarations are hoisted
function JokerController () {}
var RobinController, // Declarations are hoisted
JokerController;
RobinController = function () {} // Assign function to RobinController
// outputs "function" (declaration was hoisted to top of scope)
console.log(typeof BatmanController);
// outputs "function" (assignment of number hasn't happened yet)
console.log(typeof RobinController);
JokerController = 1; // Assign number to JokerController
// outputs "number" (assignment of number has now happened)
console.log(typeof JokerController);
}());
有关完整的技术细节,我建议您阅读 section 10.5 of the spec .
关于javascript - 为什么在 JavaScript 中局部变量名优先于函数名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13156209/