Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototyping "arguments" [closed]

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?

like image 934
Lars Knickrehm Avatar asked Jul 18 '26 15:07

Lars Knickrehm


1 Answers

the arguments object is not a type, it is a generic Object. In order to extend it's prototype, you would have to extend the prototype of Object, which is generally not a good idea.

There is nothing wrong with converting arguments to an Array using Array.prototype.slice.

Let's say I was to extend the arguments prototype:

arguments.constructor.prototype.foo = 'bar';

The problem here is that arguments.constructor is not some Argument object, it's just Object. Now if I try to do something that should work normally, it's fubar'd:

var someNewObject = {
    someProperty: 'someValue'
};

for (var item in someNewObject) {
    console.log(item);  // logs someProperty AND foo, not good
}

You can see this in action here.

like image 177
jbabey Avatar answered Jul 20 '26 04:07

jbabey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!