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

坚强是说给别人听的谎言 提交于 2019-11-28 16:18:45

问题


1.

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

v/s

2.

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

Kindly explain from beginners point.


回答1:


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:

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.



回答2:


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



来源:https://stackoverflow.com/questions/18828874/difference-between-function-with-a-name-and-function-without-name-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!