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

后端 未结 8 1667
半阙折子戏
半阙折子戏 2021-01-29 23:43

How to write this in coffeescript?

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

Thanks for any tips :)

8条回答
  •  渐次进展
    2021-01-29 23:47

    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.

提交回复
热议问题