This is kind of a lame work around, but it works. Hopefully there is a
better solution.
I probably shouldn’t have asked - I found out that you can do this but
not defaulting in the function definition.
You have to interrogate the built-in Javascript “arguments” array to see
if there are extra arguments and then default them based on your needs,
etc.
There is no explicit contract between the caller and the callee - I can
pass as many arguments as I want to a Javascript function and the number
of arguments that it receives can be less.
In this way, Javascript is even more dynamic than Ruby in it’s calling
semantics since Ruby will throw a run time error if you call a function
with the wrong number of parameters - as I’m sure all of us Railists
know :)!
?
There is no language support for it but there are ways to emulate it
since Javascript does not require you to send all arguments. Eg.
function X(a, b, c) {
if( arguments.length < 3 ) c = ‘dog’
if( arguments.length == 1 ) b = false
//... implementation
}
Some people will use the short-circuited “or” operator as follows:
function Y(m, n, o) {
n = n || ‘foo’
o = o || ‘bar’
//... implementation
}
This can be dangerous if a valid value for “n” or “o” can evaluate to
false. In Ruby only “nil” and “false” evaluate to false but in
Javascript the follow all evaluate to false:
undefined
null
0
-0
“” (empty string)
NaN
An empty string and 0 are often valid values. Prototype has this fault
in it’s implementation of the $F() function for input elements.
Another entirely different option is to use object literals to emulate
optional named arguments. So:
function M(name, options) {
defaults = {
foo: ‘bar’,
baz: ‘cat’
}
options.prototype = defaults
//… implementation using “options” to access
//… optional arguments
}
You would call this like:
M(‘some_val’, {
foo: ‘dog’,
baz: ‘car’
});
If you remove an option it would get the default specified. So:
M(‘another_val’, { foo: ‘dog’ });
Eric
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.