在John Resig的“学习高级Javascript”幻灯片#6(http://ejohn.org/apps/learn/#6)中显示,您可以在定义函数之前使用它。这里是代码:在定义之前使用javascript函数
var canFly = function(){ return true; };
window.isDeadly = function(){ return true; };
assert(isNimble() && canFly() && isDeadly(), "Still works, even though isNimble is moved.");
function isNimble(){ return true; }
但是,我注意到下面的代码没有通过测试。
assert(canFly(), "Still works, even though isNimble is moved.");
var canFly = function(){ return true; };
它看起来像一个匿名函数分配给一个变量不同于定义一个命名函数。这是为什么?这个概念的名称是什么,它描述了在语言定义之前使用函数的能力?
[JavaScript'hoisting']的可能重复(http://stackoverflow.com/questions/15311158/javascript-hoisting) –
搜索条件是“JavaScript hoisting” - 检查链接的副本(使用稍有不同的代码,但良好的链接) - 整个函数的变量是可见的(在'var'之前的方式),但只会在第一次赋值期间得到值。 –
@AlexeiLevenkov对于范围而不是事物的顺序,最重要的不是答案吗? –