开发者

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?


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.


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

compiles to

(function($, window) {
  return $(function() {
    return alert("js!");
  });
})($, window);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜