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?
undefinedis a keyword in CoffeeScript. You don’t need to ensure it’s properly defined, so you can forget that part.CoffeeScript provides a
dokeyword that you can use to create a closure instead of using the immediately-invoked function expression syntax.CoffeeScript Source try it
Compiled JavaScript
The above syntax wasn’t supported until CoffeeScript 1.3.1. For older version you still need to do this:
CoffeeScript Source [try it]
If you’re curious, here’s how CoffeeScript handles
undefined.CoffeeScript Source [try it]
Compiled JavaScript
You can see that it doesn’t use the
undefinedvariable, but instead uses JavaScript’svoidoperator to produce the undefined value.