在定义之前使用javascript函数
在John Resig的“Learning Advanced Javascript”幻灯片中,#6()显示了您可以在定义函数之前使用它。代码如下:在定义之前使用javascript函数,javascript,function,variables,scope,Javascript,Function,Variables,Scope,在John Resig的“Learning Advanced Javascript”幻灯片中,#6()显示了您可以在定义函数之前使用它。代码如下: var canFly = function(){ return true; }; window.isDeadly = function(){ return true; }; assert( isNimble() && canFly() && isDeadly(), "Still works, even though
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创建执行上下文时,它首先创建所有变量、函数和参数。接下来,它为它们赋值。由于
isNimble
是一个全局定义的函数,它是在第一阶段与canFly
一起创建的,但是canFly
直到第二阶段赋值后才被赋值。赋值不会在执行assert语句之前发生
见:
下面是上述链接的摘录,可以很好地解释这一点:
详细的执行上下文
现在我们知道,每次调用函数时,都会有一个新的执行
上下文被创建。但是,在JavaScript解释器中,每个
对执行上下文的调用有两个阶段:
Creation Stage [when the function is called, but before it executes any code inside]:
Create variables, functions and arguments.
Create the Scope Chain.
Determine the value of "this".
Activation / Code Execution Stage:
Assign values, references to functions and interpret / execute code.
这是为什么会发生(而且必须发生)的答案。这不太依赖于语言,我只是希望我没有对javascript使用奇怪的术语 当您处于代码中的某一点时,您应该知道调用函数时会发生什么。因此,函数通常只定义一次,或者已知优先级顺序。函数并不是为了改变而设计的,所以让用户可以使用它们是有意义的,即使它们是在代码的底部定义的 调用变量时,您希望在调用该变量时获得该变量的值。如果在调用变量之前没有定义它,那么它应该不会工作。除其他外,这允许您在代码中的不同点为同一变量分配不同的函数
这样得出结论:不要混淆“后”和“下”,只考虑简单的函数定义发生在变量赋值之前(即使你给该变量赋值)。-整个函数的变量可见(在
var
之前),但只会在第一次赋值时得到值。@AlexeiLevenkov不是最重要的答案,更多的是关于范围而不是事情的顺序?@DennisJaheruddin-多少-但你可以把它理解为一种解释,说明在范围末尾声明的函数如何在范围开始时立即可见。它实际上取决于语言-以及JavaScript将所有声明移动到范围的顶部(提升)。如果在声明之前使用变量/函数,某些语言可能会出现错误…”“因为isNimble
是一个全局定义的函数”应该是“因为isNimble
是使用函数声明定义的”。在引用的文本中,请注意ThisBinding是先设置的,而不是最后设置的。
var canFly = function(){ return true; };
Creation Stage [when the function is called, but before it executes any code inside]:
Create variables, functions and arguments.
Create the Scope Chain.
Determine the value of "this".
Activation / Code Execution Stage:
Assign values, references to functions and interpret / execute code.