Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a function and immediately call it in Coffee, can't get the desired result

Tags:

coffeescript

Can't get my Coffee script to compile exactly into:

( function (root) { return 'Hello Coffee'; }(this) );

First attempt:

do (root) ->
    'Hello Coffee'

... is not generating the same code as above, outputting (with --bare):

(function(root) {
  return 'Hello Coffee';
})(root);
like image 980
gremo Avatar asked Dec 04 '25 06:12

gremo


1 Answers

There's no reason to believe that you can get exactly that JavaScript and there's probably no reason to get exactly that JavaScript. You can get something functionally equivalent though:

((root) -> 'Hello Coffee')(@)

becomes this JavaScript:

(function(root) { return 'Hello Coffee'; })(this);

which does the same thing as your JavaScript.


The do keyword is meant for use inside loops:

When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

You'd normally use do in things like this:

for x in a
    do (x) ->
        $("##{x}").click -> console.log x

where you want to break the connection between a loop variable and its use in a closure. That's why root shows up twice in the JavaScript version of

do (root) ->
    'Hello Coffee'
like image 78
mu is too short Avatar answered Dec 07 '25 20:12

mu is too short