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);
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
dokeyword, 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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With