根据 ECMA-262,在执行任何代码之前处理函数声明。因此,在任何地方声明函数都会有效地将它们移动(“提升”)到执行上下文的顶部。
但是,并非所有看起来像声明的东西都是声明。在下面的:
if (false) {
function fred() {return true;}
}
一些浏览器会看到一个函数声明,所以:
alert(fred());
显示“真实”。其他浏览器使用 ECMA-262 的扩展,允许将其视为命名函数表达式函数语句(我将尝试找到对 Richard Cornford 在 comp.lang.javascript 上关于该内容的出色帖子的引用,见下文),以便:
alert(fred());
抛出fred未定义的错误。在 Firefox 和 IE 中尝试一下。
So the bottom line is if you want to conditionally create a function, use an unambiguous function expression. They're often used in conjunction with feature testing, e.g. to create a function to get the textContent or innerText of an element:
var getText = (function() {
var el = document.createElement('div');
if (typeof div.textContent == 'string') {
div = null;
return function(el) {return el.textContent;};
} else if (typeof div.innerText == 'string') {
div = null;
return function(el) {return el.innerText;};
}
}());
Edit
Here's Richard Cornford's post in FunctionExpression's and memory consumptions. The important part:
In fact it is a function statement; a syntax extension that is
capable of allowing the conditional creation of a function because
being a Statement it can be evaluative inside a block.
But the whole post is worth reading.
Also note that function statements are warned against in ES5 strict mode and may be introduced in some future version of ECMAScript.