Posts Tagged ‘tip’

Self-executing functions in JavaScript

Thursday, July 29th, 2010

In Ryan Florence’s excellent post comparing jQuery’s approach to Mootools’, he makes a number of interesting comparisons about each framework’s approach.

One area where jQuery provides an elegant solution is its use of anonymous functions to set DOM properties, as shown in the following snippet.

This is something that I certainly missed when working with Mootools, but fortunately there’s an easy, quick solution.

Ryan proposes the use of the setEach plugin to solve this issue, but to me, this doesn’t seem necessary. You can work around the issue by using a function that executes immediately, as follows.

The key here is the extra pair of parentheses after the function definition, which forces the function to execute straight away. Simple, quick, and it gives the same functionality as the jQuery equivalent without having to add the overhead of a plug in.