Question

I'm extending a chrome extension that is written in coffeescript and have come across this syntax:

Commands =
  init: ->
    for command, description of commandDescriptions
      @addCommand(command, description[0], description[1])

  availableCommands: {}
  keyToCommandRegistry: {}

I'd just like to check the difference between this syntax and a class (which would be like this, hypothetically):

class Commands
  init: ->
    for command, description of commandDescriptions
      @addCommand(command, description[0], description[1])

  availableCommands: {}
  keyToCommandRegistry: {}

Is it just that the former doesn't have a prototype? am I right in thinking that it's alright to call the methods on the Commands in the top, as in Commands.init(). The project I'm working in seems to use both syntaxes so I would like to be sure I understand the implications of each before I use one or another.

Thanks.

Was it helpful?

Solution

The primary implication of the first Command is that it is an Object, not a Function, so there is no way to stamp out instances of it directly.

It is a bit confusing that its init method includes commandDescriptions (which I can only expect is declared somewhere else) and @addCommand, which is not attached to the Command object. If Command didn't have @addCommand, I would expect that it is a singleton. But as a method that is not declared on Command is expected to be present, it looks like the group of functionality in Command is meant to be mixed into another class.

Edit:

To clarify, objects can have @variables. In the init function, you would reference availableCommands or keyToCommandRegistry as @availableCommands and @keyToCommandRegistry. However, in this particular example, @addCommand is not declared anywhere. I would have expected it to be declared as part of the Command object declaration, like:

CommandsA =
  init: ->
    for command, description of commandDescriptions
      @addCommand(command, description[0], description[1])

  availableCommands: {}
  keyToCommandRegistry: {}

  addCommand: (command, descriptionInfo, otherDescriptionInfo) ->
    #Does some stuff

If you can find where addCommand is declared, it would help in understanding how Command is intended to be used.

Also of note: since Command is an object and not a class, the availableCommands and keyToCommandRegistry objects can be thought of as static class variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top