简体   繁体   English

CoffeeScript中的匿名函数语法

[英]Anonymous functions syntax in CoffeeScript

I've been looking at CoffeeScript and I'm not understanding how you would write code like this. 我一直在看CoffeeScript ,我不明白你将如何编写这样的代码。 How does it handle nested anonymous functions in its syntax? 它如何在语法中处理嵌套的匿名函数?

;(function($) {
          var app = $.sammy(function() {

            this.get('#/', function() {
              $('#main').text('');
            });

            this.get('#/test', function() {
              $('#main').text('Hello World');
            });

          });

          $(function() {
            app.run()
          });
        })(jQuery);

didn't actually compile it, but this should work 实际上没有编译它,但这应该工作

(($) ->
  app = $.sammy ->

    this.get '#/', ->
      $('#main').text '' 

    this.get '#/test', ->
      $('#main').text 'Hello World'

  $(->
    app.run()
  )
)(jQuery);

Matt's answer is correct, but here's an alternative method: 马特的答案是正确的,但这是另一种方法:

In CoffeeScript 1.0 (released a few weeks after this question was posed), a do operator was introduced that runs the function that immediately follows it. 在CoffeeScript 1.0(在提出这个问题几个星期后发布)中,引入了一个do运算符,它运行紧随其后的函数。 It's mostly used for capturing variables in loops, since 它主要用于捕获循环中的变量,因为

for x in arr
  do (x) ->
    setTimeout (-> console.log x), 50

(which passes a reference to x into the anonymous function) behaves differently than (它将对x的引用传递给匿名函数)的行为与

for x in arr
  setTimeout (-> console.log x), 50

The latter will simply output the last entry in arr repeatedly, since there's only one x . 后者将只重复输出arr的最后一个条目,因为只有一个x

Anyway, you should be aware of do as a way of running an anonymous function without the extra parentheses, though its capabilities with respect to argument-passing are a bit limited at the moment. 无论如何,你应该知道的do因为没有额外的括号运行的匿名函数的一种方式,但它的功能相对于参数传递有点此刻的限制。 I've raised a proposal to broaden them . 我提出了扩大它们建议

Currently, the equivalent of your code example would be 目前,相当于您的代码示例

do ->
  $ = jQuery
  ...

If my proposal is accepted, it will be possible to write 如果我的提议被接受,则可以写

do ($ = jQuery) ->
  ...

instead. 代替。

Short variant 简短的变种

do ($=jQuery)->
 app = $.sammy ->
   @get '#/', -> $("#main").text ''
   @get '#/test', -> $('#main').text 'Hello world'
 $ -> app.run()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM