Frage

I am iterating through an object and comparing the property names against a given parameter; if there's a match, I want the property function to be executed. How would I call it other than explicitly?

The object:

@headers =
   'foo': (obj)->
       # do stuff

The routine:

resolve: ('foo', item, obj)->
   for prop of @headers
      if prop == arguments[0]
         # execute obj's foo property
War es hilfreich?

Lösung

Well, you'll need to name the 1st argument as CoffeeScript doesn't expect a string to be there.

But, if I understand correctly, you can use the ? "existential" operator (documented in a sub-section of Operators and Aliases) after a member operator:

resolve: (prop, item, obj)->
   if @headers[prop]?
      obj[prop]()

This will compile to:

resolve: function(prop, item, obj) {
  if (this.headers[prop] != null) {
    return obj[prop]();
  }
}

And, if you want to test for the method on obj as well, you can place the ? between the member operator and arguments/calling parenthesis:

obj[prop]?()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top