views:

63

answers:

2

I've been digging into jquery to find out how it works and I see it uses a construct i've never seen in JS before. The following code seems to execute when the browser loads, it's almost like a function that invokes itself. I've searched for docs for this feature but not sure what its called. Can someone tell me the principle so I can google further info on this?

(function test() {
    alert('test');
})();
+6  A: 

That's exactly what it is, a self-invoking anonymous function, the variables inside that scope:

(function test() {
  //here
})();

Won't be visible outside unless you expose them either. If you want more detail around uses and practical examples, I'd start with this question.

Nick Craver
thanks.. is this common? Anyway to tell when it's actually being invoked? (i.e.: when the script is read, compiled by the browser or when the page has completed its loading?)
Billworth Vandory
@Billworth - Yep it's *very* common. It's being invoked exactly where it occurs in your code, it's not a `document.ready` handler that jQuery uses, that's a different format, like `$(function() { })` or `$(document).ready(function() { });` or `jQuery(function($) { });`.
Nick Craver
It's true that these are commonly called "self-invoking" or "self-executing", but they don't *really* invoke themselves. Something like, "immediately invoked and discarded anonymous function" would be more accurate, but I don't think it'll catch on :-)
Pointy
+3  A: 

It is a self-executing function.

It is used to create a local scope. If you have a code-snippet that requires lots of new variables, and you only need to run that code once, then it is a good idea to encapsulate the snippet with this function (so that the variables form the snippet don't pollute the global namespace).

(function() {
    // all variables and functions declared here are not visible
    // outside of this function
})();

However, in your code, the function is not anonymous - you called it "test", so it is a named function expression. It is probably best to not define names for function expressions (because there are bugs in Internet Explorer related to this issue: http://github.com/kangax/nfe

Šime Vidas