Hi I'm wondering if its possible to omit empty parenthesis when chaining in coffeescript.
for example
myFunction = -> [...]
chain1 = -> [...]
chain2 = -> [...]
myFunction().chain1().chain2()
to instead
myFunction.chain1.chain2
That exact syntax will not work in CoffeeScript. You can only chain methods that have at least one argument, so something like this could work:
myFunction arg1
.chain1 arg2
.chain2 arg3
For jQuery, for example, you can do stuff like:
$ ->
$ '#foo'
.and '.bar'
.click ->
alert 'awesome!'
This is because, unlike in Ruby, where referencing a name without a leading '@' or '::' implies a method or a local variable, in CoffeeScript, myFunction
is an expression that returns the function itself. Thus, myFunction.chain1
and myFunction().chain1
can both be valid and mean different things.
Note however, that the new
keyword implies a function call, so if myFunction
is an (oddly named) constructor, you could write (new myFunction).chain1
, but that is again different as .chain1
would be the property of the prototype.
Moreover, if you are the author of the library in question, you could use getters/setters to simulate that behaviour in plain JavaScript, but I would highly discourage that.