Introduction
We all know these silly arguments objects of JavaScript functions.
But why object? Isn’t it an array?
No, it’s not and that’s why a lot people call it a failure in JavaScripts concept:
(function () {
return arguments.slice(); // TypeError: arguments.slice is not a function
}());
Intention
Okay, that’s just an introduction to the real thing I’d like to ask, but before asking you need some more information:
While reading different code during the last days, I got quite scarry while seeing the following line of code in quite a lot places.
args = Array.prototype.slice(arguments);
So, what does it do, is simply “converting” the arguments object into an array with all of its prototypes and stuff.
My solution
What I thought of was the following: While JavaScript is all about prototyping, why don’t we extend the arguments object’s prototype itself? I checked some sites for existing scripts, but found nothing I was intended to find and finally got to write it myself:
(function () {
var i, methods;
arguments.constructor.prototype = Array.prototype;
methods = ['concat', 'join', 'pop', 'push', 'reverse', 'shift', 'slice', 'sort', 'splice', 'toString', 'unshift'];
for (i = 0; i < methods.length; i += 1) {
if (arguments.constructor.prototype.hasOwnProperty(methods[i]) === false) {
arguments.constructor.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
}());
After compression it takes 260 byte only and extends the arguments object’s prototype by using Array.prototype.
So finally I can handle arguments objects just the same way as “real” arrays.
The question
After checking the most famous JavaScript frameworks I finished with the following: none uses such a construct and extends the arguments object’s prototype.
But why? Is there anything wrong with, I don’t think of right now?
the
argumentsobject is not a type, it is a genericObject. In order to extend it’s prototype, you would have to extend the prototype ofObject, which is generally not a good idea.There is nothing wrong with converting
argumentsto an Array usingArray.prototype.slice.Let’s say I was to extend the
argumentsprototype:The problem here is that
arguments.constructoris not someArgumentobject, it’s justObject. Now if I try to do something that should work normally, it’s fubar’d:You can see this in action here.