【问题标题】:In CoffeeScript, how should I format a function call that takes an anonymous function and other arguments?在 CoffeeScript 中,我应该如何格式化一个接受匿名函数和其他参数的函数调用?
【发布时间】:2013-08-09 13:41:47
【问题描述】:

这是我想出的一个人为的例子:

fn = (f, a, b, c)-> alert("#{f() + a + b + c}")

fn((-> "hi"), 1, 2, 3)

我想知道格式化最后一行的建议方法是什么?这个例子很容易理解,但想象一下,如果匿名函数((-> "hi"))是多行的并接受多个参数。这段代码会变得非常难看,并开始看起来像 lisp。

fn2 = (f, a, b, c)-> alert("#{f(1, 2) + a + b + c}")

fn2(((a, b) -> 
  c = a + b
  c), 1, 2, 3)

这可能会变得非常糟糕。有什么方法我应该格式化这段代码以使其更具可读性,或者是命名匿名函数的最佳建议?

我注意到一些类似的问题询问如何执行此操作。这里的区别是我在问如何格式化它。

【问题讨论】:

    标签: formatting coffeescript code-formatting


    【解决方案1】:

    这种风格我见过几次了:

    fn2 (a, b) -> 
      a + b
    , 1, 2, 3
    

    例如,在setTimeout 调用中:

    setTimeout ->
      alert '1 second has passed'
    , 1000
    

    但我认为一般来说最好将参数函数分隔在一个变量中:

    add = (a, b) -> 
      a + b
    fn2 add, 1, 2, 3
    

    或者,如果可以更改函数定义,请将函数参数设为最后一个:

    fn2 1, 2, 3, (a, b) ->
      a + b
    

    【讨论】:

      【解决方案2】:

      在 Coffeescript 文档中有一个带有函数参数 last 的示例

      task 'build:parser', 'rebuild the Jison parser', (options) ->
        require 'jison'
        code = require('./lib/grammar').parser.generate()
        dir  = options.output or 'lib'
        fs.writeFile "#{dir}/parser.js", code
      

      Coffeescript 测试文件有很多带有函数 last 的示例

      test "multiple semicolon-separated statements in parentheticals", ->
        nonce = {}
        eq nonce, (1; 2; nonce)
        eq nonce, (-> return (1; 2; nonce))()
      

      当函数不是最后一个时,你需要更混乱的缩进和逗号,或者额外的括号来定义函数的边界。

      【讨论】:

      • 同意,通常在 node.js 中,您会看到回调函数尾随,因此这是一个习惯的好习惯。
      猜你喜欢
      • 2022-08-16
      • 1970-01-01
      • 2011-10-06
      • 2016-09-09
      • 2012-04-18
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多