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

坚强是说给别人听的谎言 提交于 2019-12-02 14:05:55

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.

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 ) 

it's ridiculous easy in coffee:

do ->

will return

(function() {})();

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

try to use

do ($ = jQuery) ->
do ->
    #your stuff here

This will create a self executing closure, which is useful for scoping.

Apologies, I solved it:

f = (
    () -> "something"
)()

It should be

f = () ->
  # do something
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!