small question on js syntax
I s开发者_如何学Goaw this syntax many times but I couldn't find a way to google it properly, I hope I can get some help here:
<script>
(function(){
//code goes here
})();
</script>
Why is the function keyword wrapped in the parenthesis? What does it do and what is this called?
In js, the syntax:
function() { //code }
defines an anonymous function. You can store this into a variable and call it:
var a = function() { //code };
a();
or if you don't want to bother assigning it you can do it in one step.
(function() { //code })();
the parenthesis are necessary because:
function() { //code }();
is not proper syntax.
This syntax is useful in certain situations to help memory management as well as change variable names. For example in javascript you have a jQuery
object, but most people refer to it as $
. But sometimes $
is used as some other variable instead of the jQuery object. To fix this, you can wrap your code in:
(function($) { // code that uses $ })(jQuery);
That way you can use the dollar sign and not have to worry whether or not it actually points to the jQuery object or not.
It is called an anonymous function that is being called immediately.
// defining and calling a named function
function x() { /* do something */ }
x();
// defining an anonymous function (usually to assign it to a variable)
var x = function () { /* do something */ };
x();
// defining and calling an anonymous function in one step
(function () { /* do something */ })();
Most often the last pattern is used as part of creating a closure.
You can google (or search on Stack Overflow) JavaScript anonymous function
or closure
Some links:
- http://en.wikipedia.org/wiki/Anonymous_function
- http://jibbering.com/faq/notes/closures/
See Bob Fincheimers answer for an explaination of what it means.
It is used to wrap a bunch of functions and variables that the programmer doesn't want to be visible from the outside - that's good when you're using libraries or so, you don't want them to block many function names for internal stuff.
精彩评论