javascript 如何在 CoffeeScript 中编写这个 lambda 闭包?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7170446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:11:16  来源:igfitidea点击:

How to write this lambda closure in CoffeeScript?

javascriptcoffeescript

提问by Thank you

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

我正在尝试使用 CoffeeScript 重新创建这个流行的 jQuery lambda 闭包:

(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'

错误:第 1 行解析错误:意外的“BOOL”

It looks like undefinedis the cause of the problem here. Any ideas on how to get around this ?

看起来undefined是这里问题的原因。关于如何解决这个问题的任何想法?

回答by Facebook Staff are Complicit

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

undefined是 CoffeeScript 中的关键字。你不需要确保它被正确定义,所以你可以忘记那部分。

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

CoffeeScript 提供了一个do关键字,您可以使用它来创建闭包,而不是使用立即调用的函数表达式语法。

CoffeeScript 源代码 try it试试看
do ($ = jQuery, window) ->  
  $ ->  
    alert "js!"
编译的 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 1.3.1 才支持上述语法。对于旧版本,您仍然需要这样做:

CoffeeScript 源代码 [try it][试试看]
(($, window) ->
  $ ->
    alert "js!"
)(jQuery, window)


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

如果您好奇,这里是 CoffeeScript 如何处理undefined.

CoffeeScript 源代码 [try it][试试看]
console.log undefined
编译的 JavaScript
console.log(void 0);

You can see that it doesn't use the undefinedvariable, but instead uses JavaScript's voidoperatorto produce the undefined value.

您可以看到它没有使用undefined变量,而是使用JavaScript 的void运算符来生成未定义的值。

回答by austinbv

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

compiles to

编译为

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