JavaScript - Why is this function declaration created in a function expression “undefined”?

后端 未结 3 1372
执念已碎
执念已碎 2020-11-30 15:25

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 de

相关标签:
3条回答
  • 2020-11-30 16:09

    It seems that if I create a function expression (p) that seems to contain a function declaration

    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.

    0 讨论(0)
  • 2020-11-30 16:12

    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'
    >
    
    0 讨论(0)
  • 2020-11-30 16:22

    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.

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

    0 讨论(0)
提交回复
热议问题