为什么我可以在 JavaScript 中定义函数之前使用它? [英] Why can I use a function before it's defined in JavaScript?

查看:29
本文介绍了为什么我可以在 JavaScript 中定义函数之前使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码始终有效,即使在不同的浏览器中:

This code always works, even in different browsers:

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();

不过,我找不到一个关于它为什么应该工作的参考.我第一次看到这个是在 John Resig 的演讲笔记中,但只是提到了.那里或任何地方都没有关于此事的解释.

I could not find a single reference to why it should work, though. I first saw this in John Resig's presentation note, but it was only mentioned. There's no explanation there or anywhere for that matter.

有人能指教我吗?

推荐答案

function 声明很神奇,它会在执行其代码块* 中的任何内容之前绑定其标识符.

The function declaration is magic and causes its identifier to be bound before anything in its code-block* is executed.

这与带有 function 表达式的赋值不同,后者以正常的自上而下的顺序进行计算.

This differs from an assignment with a function expression, which is evaluated in normal top-down order.

如果您将示例更改为:

var internalFoo = function() { return true; };

它会停止工作.

函数声明在语法上与函数表达式完全不同,尽管它们看起来几乎相同并且在某些情况下可能不明确.

The function declaration is syntactically quite separate from the function expression, even though they look almost identical and can be ambiguous in some cases.

这在 ECMAScript 标准,部分 <强>10.1.3.不幸的是,即使按照标准标准,ECMA-262 也不是一个非常易读的文档!

This is documented in the ECMAScript standard, section 10.1.3. Unfortunately ECMA-262 is not a very readable document even by standards-standards!

*:包含函数、块、模块或脚本.

*: the containing function, block, module or script.

这篇关于为什么我可以在 JavaScript 中定义函数之前使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆