I prefer checking == null instead of typeof(arg1) === undefined (as the jQuery library does internally: http://docs.jquery.com/JQuery_Core_Style_Guidelines#JSLint ). It is not only shorter, but also handles both null and undefined, so client code can pass in null and get by default.
It is also possible to wrap a function in another function that supplies default values. The prototypejs library has a function that provides argumentNames() (or if you don't want to use a prototype, you can just borrow the implementation - it's just a regular expression that applies to the results of the toString() function).
So you can do something like this:
var Foo = defaults(Foo, { arg1: 50, arg2: 'default' }); function Foo(arg1, arg2) {
And the defaults() implementation will look something like this:
function defaults(fn, def) { return function() { var arg_names = fn.argumentNames(); var nArgs = args.length; for (var nArg = 0; nArg < nArgs; ++nArg) { if (arguments[nArg] == null && arg_names[nArg] in def) arguments[nArg] = def[arg_names[nArg]]; } fn.apply(this, arguments); } }
Of course, this unverified code and how to write it requires the Prototype library. But all that said, the == null approach inside the function is more natural for Javascript, itโs easier to debug (you donโt have another functional level for the transition), and itโs easier for me to read:
function Foo(arg1, arg2) { if (arg1 == null) arg1 = 50; if (arg2 == null) arg2 = 'default'; }
Peter Rust
source share