Expansive Argument Handling
CoffeeScript provides an excellent syntax for handling a wide range of scenarios for expected function arguments. Here are some examples of a few (some more known than others).
Splats: Allows you more control of a function's arguments when there could an uncertain amount of parmeters passed:
(first, others..., last) ->
The first
and last
arguments will be stored in there respective variables, and all arguments in between those two will be stored as an array in the other
variable.
Splats are covered in the CS documentation, but less known are handling function arguments of different object types. The below functions are all valid CS:
Arrays:
([firstElement, secondElement]) ->
Results in:
(function(_arg) {
var firstElement, secondElement;
firstElement = _arg[0], secondElement = _arg[1];
});
Objects:
({firstKey, secondKey}) ->
Results in:
(function(_arg) {
var firstKey, secondKey;
firstKey = _arg.firstKey, secondKey = _arg.secondKey;
});
Instance Variables:
(@firstObjectVariable, @secondObjectVariable) ->
Results in:
(function(firstObjectVariable, secondObjectVariable) {
this.firstObjectVariable = firstObjectVariable;
this.secondObjectVariable = secondObjectVariable;
});
Written by Mark Roseboom
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Coffeescript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#