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

JavascriptJavascript FrameworkCoffeescript

Javascript Problem Overview


How to write this in coffeescript?

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

Thanks for any tips :)

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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 ) 

Solution 3 - Javascript

it's ridiculous easy in coffee:

do ->

will return

(function() {})();

Solution 4 - Javascript

try to use

do ($ = jQuery) ->

Solution 5 - Javascript

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

Solution 6 - Javascript

do ->
    #your stuff here

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

Solution 7 - Javascript

Apologies, I solved it:

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

Solution 8 - Javascript

It should be

f = () ->
  # do something

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser537339View Question on Stackoverflow
Solution 1 - JavascriptTrevor BurnhamView Answer on Stackoverflow
Solution 2 - JavascriptMisha ReyzlinView Answer on Stackoverflow
Solution 3 - Javascriptmart7iniView Answer on Stackoverflow
Solution 4 - JavascriptPavel BlagodovView Answer on Stackoverflow
Solution 5 - JavascriptXåpplI'-I0llwlg'I -View Answer on Stackoverflow
Solution 6 - JavascriptJordan CheckmanView Answer on Stackoverflow
Solution 7 - Javascriptuser537339View Answer on Stackoverflow
Solution 8 - JavascriptAlongkornView Answer on Stackoverflow