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

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

问题描述

Javascript 代码

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.

所以,上面将是

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

因此 d 是对命名函数 c 的引用

Hence d is a reference to a named function c

  1. 在执行 d() 时,函数 c 在全局范围内执行,其中没有名为 c 的变量或属性.但是控制台仍然设法记录 c 的函数定义.
  2. 当我尝试 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]

案例2证明没有名为c的窗口属性可用那么,d() 如何在执行时打印 c 的定义?

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.

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

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

另请参阅ECMAScript 5 规范的相关部分.它对此有特别说明.

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

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

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