What does this JavaScript snippet mean? [duplicate]

不羁岁月 提交于 2019-11-26 14:39:23

问题


This question already has an answer here:

  • What is the (function() { } )() construct in JavaScript? 23 answers

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

(function(fun) { 

})(myFunkyAlert);

回答1:


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".




回答2:


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




回答3:


Refer to this question: What is the difference between a function expression vs declaration in JavaScript? and this link: http://kangax.github.com/nfe/



来源:https://stackoverflow.com/questions/6771406/what-does-this-javascript-snippet-mean

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