Updated 2008.01.28: Great idea from Marc and Hendrik. Very slick.
function concatenate(){ // return arguments.join(''); // won't work. arguments is not a real array. // return [].splice.call(arguments,0).join(''); // old 'n busted return Array.prototype.join.call(arguments,''); // new hotness } concatenate('good',2,'go'); // ==> 'good2go'
5 comments ↓
function concatenate() {
return Array.prototype.join.call(arguments, '');
}
@Marc, while I do like how yours is cleaner from a syntax POV, I'm of the camp who say extending native objects is verboten.
Uh, Marc isn't extending anything. He's just calling the built-in join() function and setting its 'this' to the 'arguments' object.
The 'arguments' object has a length and can be accessed with [index], and that's enough for join() to run.
Ecma-262 specifically tells you they've been anticipating that:
"The join function is intentionally generic; it does not require that its this value be an Array object.
Therefore, it can be transferred to other kinds of objects for use as a method."
Ah, that's totally cool!
If join() did require its input be arrays then we'd go with the [].splice method, but this is much nicer.
Hmm that makes me think:
What other functions get used like this? (Hijacking their methods for use with other objects?)
That new hotness method is really nice! And of course it brings a warm fuzzy feeling knowing that the join function was even intended to be used like that.
Ok, these Javascript notes of yours mr. Irish hereby require me to add you to my RSS reader ;)