Multiple Arguments
In the Math.max
example above,
weâre using ...
to de-structure the
array and passing it as multiple arguments to max
. Behind the scenes, CoffeeScript is
converting the function call to use apply()
, ensuring the array is passed as
multiple arguments to max
. We can use
this feature in other ways too, such as proxying function calls:
Log = log: -> console?.log(arguments...)
Or you can alter the arguments before theyâre passed onwards:
Log = logPrefix: "(App)" log: (args...) -> args.unshift(@logPrefix) if @logPrefix console?.log(args...)
Bear in mind though that CoffeeScript will automatically set the
function invocation context to the object the function is being invoked
on. In the example above, that would be console
. If you want to set the context
specifically, then youâll need to call apply()
manually.
Get The Little Book on CoffeeScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.