即使在不同的浏览器中,此代码也始终有效:
function fooCheck() {
alert(internalFoo()); // We are using internalFoo() here...
return internalFoo(); // And here, even though it has not been defined...
function internalFoo() { return true; } //...until here!
}
fooCheck();
Run Code Online (Sandbox Code Playgroud)
但是,我无法找到它应该起作用的单一参考.我第一次在John Resig的演示文稿中看到过这个,但它只是提到了.那里或其他任何地方都没有解释.
有人可以赐教吗?
请将官方ECMAScript规范视为您的答案来源,而不是特定浏览器供应商发布的文档.(我知道Mozilla使用"函数语句"扩展其JavaScript实现.)
那么,根据ECMAScript规范,ergo,其中定义的句法产品,这是有效的吗?
if (foo) {
function x() { return; }
}
Run Code Online (Sandbox Code Playgroud)
更新:我的问题也可以这样说: Statement生产是否包含 FunctionDeclaration生产?
结论:答案是否定的.
我曾经认为函数总是被提升到任何JavaScript代码块的顶部.
例如,这有效:
document.addEventListener('something', dummy);
function dummy(){
console.log('dummy');
}
Run Code Online (Sandbox Code Playgroud)
但这不适ReferenceError用于Firefox,但在Chrome中有效:
if(document){
document.addEventListener('something', dummy1);
function dummy1(){
console.log('dummy');
}
}
Run Code Online (Sandbox Code Playgroud)
最初,我认为Chrome在我测试之前也会抛出错误,但不知怎的,它可以正常工作.有人可以解释为什么它在Firefox中不起作用?