为什么名称功能表达式在函数体外不可用 [英] Why a Name Function Expression not available outside function body

查看:87
本文介绍了为什么名称功能表达式在函数体外不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

命名函数表达式,定义为

The Named Function Expression which is defined as

var ninja = function myNinja();

有一种无法解决的行为。

has a behavior which is not able to get through my head.

查看以下代码

 var ninja = function myNinja() {
   console.log(typeof myNinja) //prints 'function'
 };
 console.log(typeof myNinja) //prints 'undefined'

现在, myNinja 是一个命名函数,据我所知,javascript允许命名函数超出其自身函数的范围。

Now, myNinja is a named function and as far as I know javascript allow the named function to go beyond the scope of its own function.

这让我感到困惑。

推荐答案


现在, myNinja 是一个命名函数,据我所知javascript允许命名函数超出其自身函数的范围。

Now, myNinja is a named function and as far as I know javascript allow the named function to go beyond the scope of its own function.

仅在函数声明中。对于命名函数表达式,具体而言。这就是规范中如何定义的。

Only in a function declaration. It's specifically not the case for a named function expression. It's just how this is defined in the specification.

所有血腥细节都是在规范中,最相关的位是:

All the gory details are in the spec, the most relevant bit is:


注意 FunctionExpression 中的 Identifier 可以从 FunctionExpression的 FunctionBody 中引用,以允许该函数以递归方式调用自身。但是,与 FunctionDeclaration 不同, FunctionExpression 中的标识符无法引用,也不会影响包含 FunctionExpression <的范围/ em>。

NOTE The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.

因此,如果您将代码更改为:

So if you changed your code to:

function myNinja() {
    console.log(typeof myNinja) //prints 'function'
}
var ninja = myNinja;
console.log(typeof myNinja) //prints 'function' (now we're using a declaration)

...因为它使用函数声明 myNinja 被添加到定义它的范围。 (声明也像所有声明一样被悬挂;它不像表达式那样作为逐步代码的一部分进行处理。)

...since that uses a function declaration, myNinja is added to the scope in which it's defined. (The declaration is also hoisted, like all declarations; it's not processed as part of the step-by-step code the way expressions are.)

这篇关于为什么名称功能表达式在函数体外不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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