Javascript default parameters
I for one absolutely hate the feature of untyped languages that forces only one method signature to be defined. Not necessarily the part where there's only one signature, so much as the inability to define parameters as optional. In php, one can specify certain later parameters to have default values. If omitted, those parameters will default, allowing the function to perform as expected. In javascript however, as in perl and other untyped languages, the developer must deal with this issue when defining the function, documenting it, and then calling it. This is just absolutely unacceptable. It allows for sloppy coding on either end, and the ability for "loose" functions which take ridiculous combinations of parameters which are so unintuitive as to render the function utterly useless. Still, it can be done clean enough for some likes, but it could be handled so much better.
For this reason, I decided, through inspiration and necessity, to engineer a helper for this issue. It can be used as a utility of the Function global object, or refactored to be applied to the Function prototype. It is largely the same either way. To make the function short, I'm using a prototype-like utility function, $A, which casts an array-like object into a proper array.Function.default = function(__method) {
if (!arguments.length || arguments.length < 2) {
return __method;
}
var args = $A(arguments).slice(1);
return function() {
return __method.apply(this, $A(arguments).concat(args.slice(arguments.length)));
};
};
As a note, if the caller or function enhancing code itself is passing the wrong number of arguments, the function will perform as if the wrong number of arguments was passed to the original function. Which, as we all know, is the developers fault, not mine.function fn(var1, var2, var3) {
alert(var1 + "::" + var2 + "::" + var3);
}
var fn2 = Function.default(fn, "test", "test2", "test3");
fn2(); // all defaults are used
fn2("a", "b"); // last default is used
fn2("a", "b", "c", "d"); // final argument ignored, as expected
var fn3 = Function.default(fn, "test");
fn3(); // first default used, final two parameters undefined, as expected
0 comments:
Post a Comment