Coffeescript --- How to create a self-running anonymous function?

How to write this in coffeescript?

f = (function(){ // something })(); 

Thanks for any advice :)

+86
javascript coffeescript javascript-framework
Apr 09 2018-11-11T00:
source share
8 answers

Although you can simply use parentheses (e.g. (-> foo)() , you can avoid them with the do keyword:

 do f = -> console.log 'this runs right away' 

The most common use of do is to capture variables in a loop. For example,

 for x in [1..3] do (x) -> setTimeout (-> console.log x), 1 

Without do you simply print the value of x after the loop 3 times.

+159
Apr 09 '11 at 19:50
source share

If you want the "alias" arguments passed to the self-invoking function in CoffeeScript, and let this be exactly what you are trying to achieve:

 (function ( global, doc ) { // your code in local scope goes here })( window, document ); 

Then do (window, document) -> will not let you do this. The path to go goes with partners then:

 (( global, doc ) -> # your code here )( window, document ) 
+19
Oct 12 '11 at 6:45
source share

It's funny easy in coffee:

 do -> 

will return

 (function() {})(); 
+15
Jul 10 '14 at 7:01
source share

try using

 do ($ = jQuery) -> 
+5
Nov 19 '13 at 11:27
source share

You can also combine the do keyword with the default function parameters to cut out recursive "self-initializing functions" with the initial value. Example:

 do recursivelyPrint = (a=0) -> console.log a setTimeout (-> recursivelyPrint a + 1), 1000 
+5
Jun 05 '14 at 15:18
source share
 do -> #your stuff here 

This will create a self-closing which is useful for defining scope.

+3
Feb 05 '15 at 22:23
source share

Sorry, I decided:

 f = ( () -> "something" )() 
+1
Apr 09 2018-11-11T00:
source share

It should be

 f = () -> # do something 
0
Jun 15 '16 at 3:01
source share



All Articles