Wednesday, April 1, 2009

A special form of function creation in Javascript

If you read source code of Dojo, you'll notice many files (e.g. dojo.js) have this structure: (function() { ...... })(); What's it for?

If you read source code of Dojo, you’ll notice many files (e.g. dojo.js) have this structure:

(function() { …… })();

Inside the body of the function is a whole bunch of complicated code. So what’s this structure for? What’s the difference between this structure and the more common function definition?

function() { …… }

We know function() {} defines an anonymous function. The ( ) operator around it makes it a priority, so

(function() { …… })

actually creates an anonymous function object and returns it. The ( ) after it is to execute the function. The whole statement is to create a function and execute it right away. In comparison,

function() { …… }

defines a function without execute it. This function can also accept parameters, as illustrated in this code snippet:

(function(x) {
this.myX = x;
alert(x);
})(10);

In this code, what is “this” representing? If you run this code in global scope, “this” represents Global object, which means Window object in browser environment. So if after executing the above code, you run:

alert(myX);

Browser will popup a window and show a value of 10