Crockford had this example to keep myArray from being in the global scope:
var myName = (function() {
var myArray = ['zero','one','two','three','four'];
return function(X) {
return myArray[X];
}
}()); // This function is invoked immediately
result = myName(3); // Now invoke it "for real"
Q: I don’t get why it isn’t
var myName = (function(X) {
Q: When I call myName(3), isn’t “var myArray=” executed a 2nd time?
Suppose it’s not executed a 2nd time because JavaScript knows that it’s already been defined… What about a loop or some other logic between the var stmt and the return function stmt? Wouldn’t it be executed every time?
Q: Can you name the subfunction and call it instead of calling myName?
okay, let’s break this down…
that piece sets
myNameto whatever that anonymous function returns, so if it were:myNamewould equal42. If that doesn’t make sense, this is the same thing:So in your example,
myNameis set tofunction(X){ return myArray[X] }. So myName is a function. When you call it, the only code that is run isreturn myArray[x].myArrayis kept in what is called a closure, it is only exposed to themyNamefunction and the anonymous one surrounding it.I wrote an article on closures years back that may help you: http://www.htmlgoodies.com/primers/jsp/article.php/3606701/Javascript-Basics-Part-9.htm (scroll down to the “Closures” header).