0

I know this type of question gets asked a lot, but I haven't seen any question with this type of declaration

(function(){
    myFuncName=function(myVar){
       // some logic
    };
}());

how does that differ from

function myFuncName(myVar){
// some logic
}
4

3 回答 3

1

What your doing is creating an anonymous function that also has a closure in it. Read more about closures here.

Basically a closure means that you have declared a function inside of another function. Which will let you access local variables after the first function exits.

Normally you would not be able to do this since they would be out of scope.

As for the other part. You can find a very useful guide to what's happening here Why do you need to invoke an anonymous function on the same line?.

To sum it up though, you have created an anonymous self-invoking function expression.
The self-invoking comes from the fact that () immediately follows the function expression.

于 2013-03-14T05:49:05.740 回答
1

The first one is an anonymous function and there is no way you can reference to and call it later on, so you just executes instantly ( ) once it had been created!

(function(){
    alert(1)
}())

The second one is a reference function that you can call it anytime later. It wont gets executed unless you call it explicitly

于 2013-03-14T06:00:11.280 回答
0

Here's a link which explains the the function declarations in javascript.

于 2013-03-14T05:48:39.890 回答