Javascript中没有名称的函数与名称和函数之间的区别

Shw*_*wet 29 javascript anonymous-function

1.

function abc(){
    alert("named function");
}
Run Code Online (Sandbox Code Playgroud)

V/S

2.

function(){
    alert("Un-Named function");
}
Run Code Online (Sandbox Code Playgroud)

请从初学者的角度来解释一下.

Jor*_*dan 22

它们的工作方式完全相同.只有你能够如何运行它们才是不同的.

所以示例#1你可以随时再次调用abc();.例如2,你要么必须将它作为参数传递给另一个函数,要么设置一个变量来存储它,如下所示:

var someFunction = function() {
    alert("Un-Named function");
}
Run Code Online (Sandbox Code Playgroud)

以下是如何将其传递到另一个函数并运行它.

// define it
function iRunOtherFunctions(otherFunction) {
    otherFunction.call(this);
}

// run it
iRunOtherFunctions(function() {
    alert("I'm inside another function");
});
Run Code Online (Sandbox Code Playgroud)

正如David在下面提到的,你也可以立即调用它:

(function() {
    alert("Called immediately");
})(); // note the () after the function.
Run Code Online (Sandbox Code Playgroud)

  • 为了完整性,匿名函数的另一个选项是立即调用(或自我调用)它:`(function(){alert('something');})();` (5认同)