Question

Could someone show me how to immediately invoke a function in CoffeeScript. I'm trying to accomplish something similar to this JS object literal.

WEBAPP = {
    maxHeight : function(){
        /* Calc stuff n' stuff */
        WEBAPP.maxHeight = /* Calculated value */
    }(),
    someProperty : ''
    /* ... */        
}

Is it possible or what are the workarounds?

Was it helpful?

Solution

There is do:

WEBAPP = 
  maxheight: do -> 1+1
  someProperty: ''

Which compiles to

var WEBAPP;

WEBAPP = {
  maxheight: (function() {
    return 1 + 1;
  })(),
  someProperty: ''
};

OTHER TIPS

For anyone else coming across this question, you can also combine the do keyword with default function parameters to seed recursive "immediately-invoked functions" with an initial value. Example:

do recursivelyPrint = (a=0) ->
  console.log a
  setTimeout (-> recursivelyPrint a + 1), 1000

why won't you try something like this?

square = (x) -> x * x

WEBAPP = {
   maxHeight: square(3),
   someProperty: ''
}

UPDATE

BTW: this is other workaround

WEBAPP = {
   maxHeight: (() -> 
       1 + 2
   )()
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top