JavaScript命名为函数作为表达式 [英] Javascript named function as an expression

查看:110
本文介绍了JavaScript命名为函数作为表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript代码

  var d =函数c(){console.log(c); }; 
d(); // function c(){console.log(c); };
c(); //引用错误

我理解变量提升的概念,其中变量声明和函数定义被提升到顶部现有范围。函数表达式中的函数定义也不会被挂起。

因此,以上将是

  var d; 
d =函数c(){console.log(c); };
d();
c();

因此d是对一个命名函数c的引用
$ b $执行 d()时,函数c在全局作用域中执行,其中没有变量或名为c的属性。但仍然控制台管理记录c的功能定义。

  • 当我尝试 c()时,我得到了一个参考错误。 [按我的意思]

  • 案例2证明没有名为c的窗口属性可用
    那么,How < c $ c> d()管理打印c的执行定义?



    每个函数在其本地范围中都有自己的定义作为属性吗?

    解决方案 DIV>

    是。一个命名的函数表达式只在该函数的作用域内产生一个对应于该函数名称的变量。



    下面是关于这个主题的一篇优秀但很长的文章: http://kangax.github.com/nfe/



    另请参阅 ECMAScript 5规范的相关部分。它有一个关于这方面的具体说明。


    Javascript Code

    var d = function c() { console.log(c); };
    d(); // function c() { console.log(c); }; 
    c(); // Reference Error
    

    I understand the concept of variable hoisting where variable declarations and function definitions are hoisted to top of the existing scope. Also function definition in function expressions are not hoisted.

    So, above will be

    var d;
    d = function c() { console.log(c); };
    d();
    c();
    

    Hence d is a reference to a named function c

    1. on executing d() the function c is executed in global scope, where there is no variable or property named c. But still console manages to log function definition of c.
    2. When I tried c() I got a reference error. [As I Expected]

    Case 2 proves that there is no window property named c available So, How did d() manage to print the c's definition on execution?

    Does every function have its own definition in its local scope as a property?

    解决方案

    Yes. A named function expression produces a variable corresponding to the function name within the scope of that function only.

    Here's an excellent but lengthy article on the subject: http://kangax.github.com/nfe/

    See also the relevant section of the ECMAScript 5 spec. It has a specific note about this.

    这篇关于JavaScript命名为函数作为表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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