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

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

问题描述

这段代码在任何浏览器中都可以正常工作:

  function fooCheck(){
alert(internalFoo )); //我们在这里使用了internalFoo()...

return internalFoo(); //在这里,即使它没有被定义...

function internalFoo(){return true; } //...直到这里!
}

fooCheck();

尽管如此,我无法找到它为什么应该起作用的单一参考。
我在John Resig的演示文稿中首先看到了这一点,但只是提到了它。



有人请赐教吗?

解决方案 函数声明是神奇的,它的标识符在其代码块*中的任何内容被执行之前被绑定。



这与函数表达式的赋值不同,后者按正常的自上而下顺序进行计算。



如果您将示例更改为:

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

它将停止工作。



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



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

包含函数,块,模块或脚本。

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

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.

Could someone please enlighten me?

解决方案

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

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

If you changed the example to say:

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

it would stop working.

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

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天全站免登陆