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

后端 未结 8 1546
半阙折子戏
半阙折子戏 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.

    0 讨论(0)
  • 2021-01-29 23:49

    it's ridiculous easy in coffee:

    do ->
    

    will return

    (function() {})();
    
    0 讨论(0)
  • 2021-01-29 23:51

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

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

    Then do (window, document) -> won't let you do that. The way to go is with parens then:

    (( global, doc ) -> 
      # your code here
    )( window, document ) 
    
    0 讨论(0)
  • 2021-01-29 23:55

    Apologies, I solved it:

    f = (
        () -> "something"
    )()
    
    0 讨论(0)
  • 2021-01-29 23:58

    You can also combine the do keyword with default function parameters to seed recursive "self-initiating functions" with an initial value. Example:

    do recursivelyPrint = (a=0) ->
      console.log a
      setTimeout (-> recursivelyPrint a + 1), 1000
    
    0 讨论(0)
  • 2021-01-30 00:06

    try to use

    do ($ = jQuery) ->
    
    0 讨论(0)
提交回复
热议问题