Another way to have a function invoked immediately is during variable
declaration:
var a = function() { return 3; }()
if/when the result of the call is needed/used later on.
Or using array notation to build an (unused) array:
[ function() { return 3; }() ]
--
Diego
On Thu, May 12, 2011 at 11:25 AM, Nick Morgan <[email protected]> wrote:
> There's a section in Ben Alman's blog about Immediate Invoked Function
> Expressions that shows the various ways you can make a function
> expression:
> http://benalman.com/news/2010/11/immediately-invoked-function-expression/
>
> // Either of the following two patterns can be used to immediately invoke
> // a function expression, utilizing the function's execution context to
> // create "privacy."
>
> (function(){ /* code */ }()); // Crockford recommends this one
> (function(){ /* code */ })(); // But this one works just as well
>
> // Because the point of the parens or coercing operators is to disambiguate
> // between function expressions and function declarations, they can be
> // omitted when the parser already expects an expression (but please see the
> // "important note" below).
>
> var i = function(){ return 10; }();
> true && function(){ /* code */ }();
> 0, function(){ /* code */ }();
>
> // If you don't care about the return value, or the possibility of making
> // your code slightly harder to read, you can save a byte by just prefixing
> // the function with a unary operator.
>
> !function(){ /* code */ }();
> ~function(){ /* code */ }();
> -function(){ /* code */ }();
> +function(){ /* code */ }();
>
> On 11 May 2011 23:00, tibolan <[email protected]> wrote:
>> Hi,
>>
>> I was just reading the source code of a script, and i found a strange
>> implementation:
>>
>> !function (){
>> //
>> }()
>>
>> After some test, it seems to do the same thing than:
>>
>> (function (){
>> //
>> })();
>>
>> is there another difference between this two way of doing the same
>> thing, if we set aside the saving of 1 char :D ?
>>
>>
>> --
>> 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]
>>
>
>
>
> --
> Nick Morgan
> http://skilldrick.co.uk
> @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]