使用命名函数表达式有什么意义? [英] What is the point of using a named function expression?

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

问题描述

我正在浏览此博客,讨论函数声明和函数表达式之间的区别.

I'm going through this blog about the difference between function declarations and function expressions.

给出了两个例子.他们称第一个为匿名函数表达式",第二个为命名函数表达式".

It gives these two examples. They call the first an "anonymous function expression" and the second a "named function expression."

// anonymous function expression
var a = function(){
   return 3;
}

// named function expression
var b = function bar(){
   return 3;
}

我在Chrome的JS控制台中测试了这两个,并且看到以下内容:

I tested these two in Chrome's JS console and I see the following:

a()
=> 3

b()
=> 3

bar()
=> bar is not defined

我的问题是:在第二个函数表达式声明中,"bar"的含义是什么?通常,为什么要使用命名函数表达式?

My question is: In the second function expression declaration, what is the point of "bar"? In general, why does one ever use a named function expression?

推荐答案

var b = function bar(){
   return 3;
}
bar()
=> bar is not defined

标识符bar仅在函数内部可用.试试

The identifier bar is only available inside of the function. Try

var b = function bar() {
    console.log(bar);
}
b();

为什么要使用命名函数表达式?

why does one ever use a named function expression?

允许引用未分配给可访问或常量变量的函数表达式,例如在 IEFE 中进行递归.

To allow referencing a function expression that was not assigned to a reachable or constant variable, e.g. for recursion in an IEFE.

此外,在调试过程中,命名函数的显示方式也有所不同,例如在调用堆栈(跟踪)或断点列表中.通常,您可以使用(命名的)函数声明而不是函数表达式,另请参见 http ://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html .

Also, named functions show up different during debugging, e.g. in call stack (trace)s or breakpoint listings. Often you can use a (named) function declaration instead of a function expression, see also http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html.

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

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