Reputation: 169
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?
Upvotes: 9
Views: 2354
Reputation: 22404
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
Upvotes: 2
Reputation: 262474
There is do
:
WEBAPP =
maxheight: do -> 1+1
someProperty: ''
Which compiles to
var WEBAPP;
WEBAPP = {
maxheight: (function() {
return 1 + 1;
})(),
someProperty: ''
};
Upvotes: 20
Reputation: 3750
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
)()
}
Upvotes: 1