For years, I've been hacking in JavaScript, as it were, "on the side". Just as a necessary, sometimes fun, often loathesome part of the webproject experience.
When doing optional parameters, I always did this:
function foo(a) {
if (arguments.length === 2)
b = arguments[1];
else
b = 'bar';
}
The problem with this is so obvious I won't even spell it out.
Here's the puncher.
What I somehow managed to miss until today, is that you can also do this:
function foo(a, b) {
if (typeof(b) === 'undefined')
b = 'bar';
}
Shorter, sweeter, more obvious. If I'd just known this a bit earlier.
Keine Kommentare:
Kommentar veröffentlichen