javascript Javascript中带名字的函数和不带名字的函数的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18828874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:21:27  来源:igfitidea点击:

Difference between function with a name and function without name in Javascript

javascriptanonymous-function

提问by Shwet

1.

1.

function abc(){
    alert("named function");
}

v/s

比/秒

2.

2.

function(){
    alert("Un-Named function");
}

Kindly explain from beginners point.

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

采纳答案by Jordan

They work exactly the same. It's only in how you are able to run them that they are different.

它们的工作原理完全相同。它们的不同之处仅在于您如何运行它们。

So example #1 you could call again at any point with abc();. For example 2, you would either have to pass it as a parameter to another function, or set a variable to store it, like this:

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

var someFunction = function() {
    alert("Un-Named function");
}

Here's how to pass it into another function and run it.

这是将它传递给另一个函数并运行它的方法。

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

// run it
iRunOtherFunctions(function() {
    alert("I'm inside another function");
});

As David mentions below, you can instantly call it too:

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

(function() {
    alert("Called immediately");
})(); // note the () after the function.

回答by Amit

Both can be used to achieve the same but the main difference is the anonymous functions don't need a name. Anonymous functions are functions that are dynamically declared at runtime. They're called anonymous functions because they aren't given a name in the same way as normal functions.

两者都可以用来实现相同的功能,但主要区别在于匿名函数不需要名称。匿名函数是在运行时动态声明的函数。它们被称为匿名函数,因为它们不像普通函数那样被命名。

Please refer this link

请参考这个链接