« Validating Arity in JavaScript 23 Jan 2015
Last week I was discussing with my pals @drslump and @ladybenko about a very simple idea I came up with while reading John Resig Secrets of the JavaScript Ninja book on Christmas holidays.
The idea is very simple: ensure that a function is called with the expected number of parameters.
A function defined like:
could be called with:
- zero parameters: name and surname will be undefined.
- one parameter: the parameter will be assigned to name, surname will be undefined.
- two parameters: the former parameter will be assigned to name, the latter to surname.
- three or more parameters: the first two parameters will be assigned to name and surname respectively, the next ones could be accessed via
arguments
.
You might want to ensure the function is always called with two parameters, so scenarios like this one won’t happen:
Let’s do the magic by defining a method in the Function prototype
:
Simply adding to our previous function the following:
Protip: adding a function to Function prototype
is usually NOT a good idea.
« Home