Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

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

1.

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

v/s

2.

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

Kindly explain from beginners point.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...