开发者

What does this JavaScript snippet mean? [duplicate]

This question already has answers here: What is the (function() { } )() construct in JavaScript? (28 answers) Closed 8 years ago.

I have not met this type of grammar before. What does it mean? To what technique is it related?

(func开发者_如何学运维tion(fun) { 

})(myFunkyAlert);


This is an anonymous function that will run as soon as it is declared. Its parameter is myFunkyAlert and inside the function it will be referenced as the fun variable.

The reason we usually write a function like that is to avoid conflicts, due to scoping.

Example:

var myFunkyAlert = "The funky alert";

(function(fun) { 
   alert(fun);
})(myFunkyAlert);

This will result in an alert with the message "The funky alert".


You're defining an anonymous function and then calling it with myFunkyAlert as an argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜