在这种情况下,咖啡脚本中的“:”是什么意思?

what does ":" mean in this case in coffee script?

我是咖啡脚本的新手。当我在看这份文件时 https://atom.io/docs/api/v0.198.0/CommandRegistry#instance-add 我看到一个代码段,

atom.commands.add 'atom-text-editor',
  'user:insert-date': (event) ->
    editor = @getModel()
    editor.insertText(new Date().toLocaleString())

虽然函数签名看起来,

::add(target, commandName, callback)

那么在代码段中,第二行的:是什么意思呢?我的理解是签名中:之前的'user:insert-date'是commandName:后面的是"callback"。所以 : 是一个像 , 这样的参数分隔符?我没有在咖啡脚本文档中找到这个介绍 http://coffeescript.org

那个冒号只是对象字面量的一部分。当没有歧义时,对象文字周围的大括号在 CoffeeScript 中是可选的。如果我们添加可选的大括号,我们得到的东西看起来更像 JavaScript:

atom.commands.add 'atom-text-editor', {
  'user:insert-date': (event) ->
    #...
}

所以 atom.commands.add 是用两个参数调用的。第一个是字符串 'atom-text-editor',第二个是具有一个键 ('user:insert-date') 的对象,其值是一个接受单个参数的匿名函数。

附加 mu 的答案太短(用户完全正确,第二个参数 commandName 可以是没有显式大括号 {} 的对象)

Atom 的源代码: https://github.com/atom/atom/blob/v0.198.0/src/command-registry.coffee#L81

add: (target, commandName, callback) ->
if typeof commandName is 'object'
  commands = commandName
  disposable = new CompositeDisposable
  for commandName, callback of commands
    disposable.add @add(target, commandName, callback)
  return disposable