javascript 如何在 CoffeScript 中传递两个匿名函数作为参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6463052/
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 20:45:56  来源:igfitidea点击:

How to pass two anonymous functions as arguments in CoffeScript?

javascriptjqueryanonymous-functioncoffeescript

提问by glortho

I want to pass two anonymous functions as arguments for jQuery's hover, like so:

我想传递两个匿名函数作为 jQuery 悬停的参数,如下所示:

$('element').hover(
  function() {
    // do stuff on mouseover
  },
  function() {
    // do stuff on mouseout
  }
);

It's easy with just one – hover ->– but what is the proper syntax in CoffeeScript for two? I tried ...hover ->, ...hover( ->..., etc. but nothing gets me the above structure.

只需要一个就很容易了hover ->——但是CoffeeScript 中两个的正确语法是什么?我试过...hover ->...hover( ->...等等,但没有什么能让我得到上述结构。

采纳答案by Joe Cheng

Put parentheses around the anonymous functions.

将括号括在匿名函数周围。

回答by Anurag

I think the problem lies with using single line comments //. Single-line comments enclosed in /* .. */seem to work fine. Here's an equivalent example with something other than a comment.

我认为问题在于使用单行注释//。包含在中的单行注释/* .. */似乎工作正常。这是一个等效的示例,其中包含注释以外的内容。

$('element').hover(
  -> console.log("first")
  -> console.log("second")
)

Or with comments using /* .. */.

或者使用/* .. */.

$('element').hover(
  -> /* first */
  -> /* second */
)

You can try these examples under the Try CoffeeScripttab. CoffeeScript adds a return statement to return the last expression of the function. If you wanted bare-bones functions which do nothing and don't contain a returnat the end, try:

您可以在Try CoffeeScript选项卡下尝试这些示例。CoffeeScript 添加了一个 return 语句来返回函数的最后一个表达式。如果您想要什么都不做return并且最后不包含 a 的基本函数,请尝试:

$('element').hover(
  () ->
  () ->
)
// $('element').hover(function() {}, function() {});

回答by kevinhyunilkim

Another way is to use backslashafter the caller function, the comma should be indented correctly.

另一种方法是在调用函数后使用反斜杠,逗号应正确缩进。

$('element').hover \
  -> # do stuff on mouseover
  ,
  -> # do stuff on mouseout