Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How to write this in coffeescript?

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

Thanks for any tips :)

like image 749
user537339 Avatar asked Apr 09 '11 13:04

user537339


1 Answers

While you can just use parentheses (e.g. (-> foo)(), you can avoid them by using the do keyword:

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

The most common use of do is capturing variables in a loop. For instance,

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

Without the do, you'd just be printing the value of x after the loop 3 times.

like image 179
Trevor Burnham Avatar answered Oct 21 '22 03:10

Trevor Burnham