That was a good article of Ben Alman... Just wanted to mention that after doing some test I found out that using "new function" to immediately invoke the function is rather slow compare to the other two patterns, up to 50% slower y some cases.

(function () {}());
(function () {})();
new function () {}; <-- slow one

I created a test case for this: http://jsperf.com/testing-parens/3

Fran

On 16/02/11 08:12, Nick Morgan wrote:
On 16 February 2011 05:16, RobG <[email protected] <mailto:[email protected]>> wrote:


    The main reason for using the grouping operator with functions that
    are executed immediately is that it lets humans reading the code know
    that when reading the first line of the function, as explained by
    Peter Michaux:


 That's not *quite* right. In the OP's question, the form

(function () {

})();

was used. In this case, the parentheses are necessary to avoid a syntax error (a function declaration needs a name and cannot be immediately executed). If you're assigning the return value of the function to a variable, then the parens are optional, and in that case I agree - they're useful to let humans reading the code know that the function will be executed immediately.

var x = (function () {

})();

Have a look at Ben Alman's piece on IIFEs for more details: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
--
Nick Morgan
http://skilldrick.co.uk
@skilldrick <http://twitter.com/skilldrick>

--
To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

--
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to