Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write this lambda closure in CoffeeScript?

I am trying to recreate this popular jQuery lambda closure with CoffeeScript:

(function($, window, undefined){
  $(document).ready(function(){
    ...
  });
})(jQuery, window);

So far I have this:

(($, window, undefined) ->
  $ ->
    alert "js!"
)(jQuery, window)

I'm getting this error:

Error: Parse error on line 1: Unexpected 'BOOL'

It looks like undefined is the cause of the problem here. How can I get around this?

like image 984
Mulan Avatar asked Aug 24 '11 04:08

Mulan


People also ask

How do you write a function in CoffeeScript?

To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.

Is CoffeeScript still a thing?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).


2 Answers

undefined is a keyword in CoffeeScript. You don't need to ensure it's properly defined, so you can forget that part.

CoffeeScript provides a do keyword that you can use to create a closure instead of using the immediately-invoked function expression syntax.

CoffeeScript Source try it
do ($ = jQuery, window) ->  
  $ ->  
    alert "js!"
Compiled JavaScript
(function($, window) {
  return $(function() {
    return console.log("js!");
  });
})(jQuery, window);

The above syntax wasn't supported until CoffeeScript 1.3.1. For older version you still need to do this:

CoffeeScript Source [try it]
(($, window) ->
  $ ->
    alert "js!"
)(jQuery, window)

If you're curious, here's how CoffeeScript handles undefined.

CoffeeScript Source [try it]
console.log undefined
Compiled JavaScript
console.log(void 0);

You can see that it doesn't use the undefined variable, but instead uses JavaScript's void operator to produce the undefined value.

like image 122
Jeremy Avatar answered Oct 05 '22 20:10

Jeremy


do ($, window) ->
  $ ->
    alert "js!"

compiles to

(function($, window) {
  return $(function() {
    return alert("js!");
  });
})($, window);
like image 27
austinbv Avatar answered Oct 05 '22 22:10

austinbv