简体   繁体   English

JavaScript - 为什么在函数表达式“未定义”中创建此函数声明?

[英]JavaScript - Why is this function declaration created in a function expression "undefined"?

I'm just trying to get my head around this function expression.我只是想弄清楚这个函数表达式。

It seems that if I create a function expression ( p ) that seems to contain a function declaration, the function declaration a() returns undefined.似乎如果我创建一个似乎包含函数声明的函数表达式 ( p ),函数声明a()返回未定义。

var p;
p = function a() { return 'Hello' }

typeof p; // returns 'function'
typeof a; // returns 'undefined'

Can anyone explain why this is the case?谁能解释为什么会这样?

And also please let me know if my terminology is off too.如果我的术语也被关闭,请告诉我。

It isn't a function declaration.它不是函数声明。 It is a function expression that happens to have a name.它是一个恰好有名称的函数表达式。 The name does not create a variable, but you can see it on the object名称不会创建变量,但您可以在对象上看到它

quentin@raston ~ $ node
> var p;
undefined
> p = function a() { return 'Hello' }
[Function: a]
> typeof p; // returns 'function'
'function'
> typeof a; // returns 'undefined'
'undefined'
> p
[Function: a]
> p.name
'a'
>

It seems that if I create a function expression (p) that seems to contain a function declaration似乎如果我创建一个似乎包含函数声明的函数表达式 (p)

No. It is a named function expression , which does not "contain" a function declaration .不是。它是一个命名函数表达式,它不“包含”一个函数声明 The name of the function expression is available as an identifier inside the function's scope (pointing to the function itself), and as the nonstandard name property .函数表达式的名称可用作函数作用域内的标识符(指向函数本身),也可用作非标准name属性

You can think of it as an anonymous function.您可以将其视为匿名函数。

The reason that this is valid is because the local function name a can be used within the function declaration for recursion, but is not valid outside of this scope.这是有效的原因是因为局部函数名称a可以在函数声明中用于递归,但在此范围之外无效。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/function https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM