javascript - 函数命名的不同方式?

标签 javascript function naming

在 Javascript 中,有什么区别:

var name = function() { //stuff to do };

{name : function() { //stuff to do } };

function name() { //stuff to do };

最佳答案

正如 Stoyan Stefanov 在 "JavaScript Patterns" 中所写:

In function declarations and named function expressions, the name property is defined. In anonymous function expressions, it depends on the implementation; it could be undefined (IE) or defined with an empty string (Firefox, WebKit):

function foo() {} // declaration
var bar = function () {}; // expression
var baz = function baz() {}; // named expression

foo.name; // "foo"
bar.name; // ""
baz.name; // "baz"

The name property is useful when debugging code in Firebug or other debuggers. When the debugger needs to show you an error in a function, it can check for the presence of the name property and use it as an indicator. The name property is also used to call the same function recursively from within itself. If you were not interested in these two cases, then an unnamed function expression would be easier and less verbose.

The case against function declarations and the reason to prefer function expressions is that the expressions highlight that functions are objects like all other objects and not some special language construct.

关于javascript - 函数命名的不同方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19709541/

相关文章:

javascript - 添加 Assets 过滤器修复后 CakePHP 主题 CSS 和 JS 损坏

javascript - 为什么 JS 在某行之后停止处理我的代码?

javascript - 如何让图像和视频完美对齐?

javascript - Prime 函数中此条件的输出是什么?

c - C 中的过程和函数

java - 返回元素集合的 Java 方法的正确命名约定是什么?

python - 如何命名一个以对象 `A` 和集合 `{A, B}` 作为参数,然后返回 `B` 的函数?

javascript - HTML/JavaScript 对可以引用另一个 HTML 文件吗?

python - 用Python编写的指令集模拟器失败

language-agnostic - 为开源库选择名称