arguments: A JavaScript Oddity

by Andrew Tetlaw

 

arguments is the name of a local, array-like object available inside every function. It’s quirky, often ignored, but the source of much programming wizardry; all the major JavaScript libraries tap into the power of the arguments object. It’s something every JavaScript programmer should become familiar with.

Inside any function you can access it through the variable: arguments, and it contains an array of all the arguments that were supplied to the function when it was called. It’s not actually a JavaScript array; typeof arguments will return the value: "object". You can access the individual argument values through an array index, and it has a length property like other arrays, but it doesn’t have the standard Array methods like push and pop.

Create Flexible Functions

Even though it may appear limited, arguments is a very useful object. For example, you can make functions that accept a variable number of arguments. The format function, found in the base2 library by Dean Edwards, demonstrates this flexibility:

function format(string) {
var args = arguments;
var pattern = new RegExp("%([1-" + arguments.length + "])", "g");
return String(string).replace(pattern, function(match, index) {
return args[index];
});
};

You supply a template string, in which you add place-holders for values using %1 to %9, and then supply up to 9 other arguments which represent the strings to insert. For example:

format("And the %1 want to know whose %2 you %3", "papers", "shirt", "wear");

The above code will return the string "And the papers want to know whose shirt you wear".

One thing you may have noticed is that, in the function definition for format, we only specified one argument: string. JavaScript allows us to pass any number of arguments to a function, regardless of the function definition, and the arguments object has access to all of them.

Convert it to a Real Array

Even though arguments is not an actual JavaScript array we can easily convert it to one by using the standard Array method, slice, like this:

var args = Array.prototype.slice.call(arguments);

The variable args will now contain a proper JavaScript Array object containing all the values from the arguments object.

Create Functions with Preset Arguments用已有参数创建函数

The arguments object allows us to perform all sorts of JavaScript tricks. Here is the definition for the makeFunc function. This function allows you to supply a function reference and any number of arguments for that function. It will return an anonymous function that calls the function you specified, and supplies the preset arguments together with any new arguments supplied when the anonymous function is called:

 arguments 对象允许我们实现很多JavaScript 技巧。下面是一个makeFunc 函数的定义,这个函数允许你提供一个函数引用及其参数,它将返回一个调用你指定函数的匿名函数,当这个匿名函数被调用的时候,它还允许你提供已有参数和任何新的参数。

function makeFunc() {
var args = Array.prototype.slice.call(arguments);
var func = args.shift();
return function() {
return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
};
}

The first argument supplied to makeFunc is considered to be a reference to the function you wish to call (yes, there’s no error checking in this simple example) and it’s removed from the arguments array. makeFunc then returns an anonymous function that uses the apply method of the Function object to call the function specified.

 

<script src="http://ads.aws.sitepoint.com/phpadsnew/www/delivery/fl.js" type="text/javascript"></script>
http://www.verisupport.com
<script type="text/javascript"> </script>

The first argument for apply refers to the scope the function will be called in; basically what the keyword this will refer to inside the function being called. That’s a little advanced for now, so we just keep it null. The second argument is an array of values that will be converted into the arguments object for the function. makeFunc concatenates the original array of values onto the array of arguments supplied to the anonymous function and supplies this to the called function.

Lets say there was a message you needed to output where the template was always the same. To save you from always having to quote the template every time you called the format function you could use the makeFunc utility function to return a function that will call format for you and fill in the template argument automatically:

var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");

You can call the majorTom function repeatedly like this:

majorTom("stepping through the door");
majorTom("floating in a most peculiar way");

Each time you call the majorTom function it calls the format function with the first argument, the template, already filled in. The above calls return:

"This is Major Tom to ground control. I'm stepping through the door."
"This is Major Tom to ground control. I'm floating in a most peculiar way."

Create Self-referencing Functions

You may think that’s pretty cool, but wait, arguments has one more surprise; it has another useful property: callee. arguments.callee contains a reference to the function that created the arguments object. How can we use such a thing? arguments.callee is a handy way an anonymous function can refer to itself.

 

repeat is a function that takes a function reference, and 2 numbers. The first number is how many times to call the function and the second represents the delay, in milliseconds, between each call. Here’s the definition for repeat:

function repeat(fn, times, delay) {
return function() {
if(times-- > 0) {
fn.apply(null, arguments);
var args = Array.prototype.slice.call(arguments);
var self = arguments.callee;
setTimeout(function(){self.apply(null,args)}, delay);
}
};
}

repeat uses arguments.callee to get a reference, in the variable self, to the anonymous function that runs the originally supplied function. This way the anonymous function can call itself again after a delay using the standard setTimeout function.

So, I have this, admittedly simplistic, function in my application that takes a string and pops-up an alert box containing that string:

function comms(s) {
alert(s);
}

However, I want to create a special version of that function that repeats 3 times with a delay of 2 seconds between each time. With my repeat function, I can do this:

var somethingWrong = repeat(comms, 3, 2000);

somethingWrong("Can you hear me, major tom?");

The result of calling the somethingWrong function is an alert box repeated 3 times with a 2 second delay between each alert.

arguments is not often used, a little quirky, but full of surprises and well worth getting to know!

<script src="http://ads.aws.sitepoint.com/adjs.php?region=136&did=adz&adtype=vertical" type="text/javascript"></script>
Share and Enjoy:

 

This post has 14 responses so far

  1. Just a quick note to point out all Arrays show as ‘object’ when you use the typeof operator. I just done the followng and got ‘object’;

    alert(typeof []);

     
  2. Gotta love the Space Oddity examples ^^

     
  3. Sounds interesting. Still a bit confused though. I will look into it though. Do you know any good documentations for?

     
  4. Excellent post on a lesser-understood topic, Andrew. One aspect of this sort of functional programming I struggle with, esp with javascript’s peculiarities, is how to make clear either thru comments or code just what is happening. Often this sort of code takes a while to decipher, even if you understand the prototypal, first-class functional javascript way. Any thoughts?

     
  5. <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushXml.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushXml.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushXml.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushXml.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushXml.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushXml.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushXml.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushXml.js" type="text/javascript"></script>

    Dougal, you’re right! Sorry for making such a noob mistake. The correct way to check is this:

      var a = [];
    alert(a.constructor.toString());

    In Firefox that will return:

    function Array() { [native code] }

    Inside a function, if you call:

      alert(arguments.constructor.toString());

    You’ll get:

    function Object() { [native code] }
     
  6. Jessie, yeah, it’s hard to write, hard to work out what the code does if you didn’t write it, and just as hard to explain what it’s dong in a blog post like this :)

    There’s lots of invisible forces at work, especially regarding scope. But once, you are familiar with the patterns, you can identify and write them easy enough.

    It makes JavaScript so expressive though, and that makes it worth persisting with.

     
  7. Really cool article!

    A couple of years ago I stumbled upon the arguments variable while writing a quick-n-dirty slideshow script. I only learned enough to do the job so it’s great to get some more insight & info from your article.

    Thanks,
    Andrew

     
  8. Don’t get me wrong, I’m a big fan of Javascript and consider it one of the most expressive languages I’ve worked with, but while it allows for some incredibly elegant solutions to problems, it also fosters a tremendous amount in-elegance in readability and clarity of purpose. I was just wondering if there are any best-practices for code layout, naming, commenting, beyond the usual programming conventions.

     
  9. Hmmm… that repeat() function is really one of those little thingy to sit down and meditate on! ;-)
    -

    I was wondering: the “apply” method should take an array as its second argument, yet you call it successfully as

    fn.apply(null, arguments);

    if made some experiments and it works just as well if you call on the “args” array created by splicing “arguments”.
    -
    On the other hand “self.apply(null,args)” doesn’t work if you call it on “arguments” instead of “args”.
    -
    Hm… ok, I got it. “self.apply(null,args)” is inside another anonymous function so “arguments” get stomped over by the new one. The power of meditation!

     
  10. Errata: the third paragraph should read:
    «I made some experiments and it works just as well if you call it on the “args” array created by splicing “arguments”».

     
  11. <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushJScript.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushJScript.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushJScript.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushJScript.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushJScript.js" type="text/javascript"></script> <script src="http://sitepointstatic.com/blogs/wp-content/plugins/code-highlight/js/shBrushJScript.js" type="text/javascript"></script>

    Trep, yeah I didn’t explain the closures that are used in the above code.

    you’ll notice the variable times, is passed to the outer function, but used in the anonymous function. Which is fine, JavaScript let’s us do that.

    However, every time a function is called the local variable arguments is created. So I can use it safely inside the inner anonymous function here:

    fn.apply(null, arguments);

    Because I know that when that anonymous function is eventually called, arguments will contain the arguments that are supplied at the time it’s called, not at the time when we are defining the anonymous function.

    However, to use setTimeout I have to create yet another anonymous function, the one that calls apply:

    function(){self.apply(null,args)}

    However, to the apply call I need to pass the original arguments that were supplied to the outer anonymous function… so I use yet another closure:

    var args = Array.prototype.slice.call(arguments);

    The args variable is defined in the outer anonymous function, but used within the inner anonymous function.

    Phew!

     
  12. instead of…
    var args = Array.prototype.slice.call(arguments);
    do this…
    var args = [].slice.call(arguments, 0);

     
  13. But don’t use arguments just for the sake of it - only if you really need to access them as a collection - because this:

    function colorize() { ... }

    is not as easy to understand at a glance, as this:

    function colorize(foreground, background) { ... }
     
  14. Hi, thanks for that brilliant article. Made a lot of things a lot clearer!
    Note: new RegExp("%([1-" + arguments.length + "])", "g"); will fail passed 9 arguments (the regexp would be "%([1-10])" so it will only match %0 and %1).

    I think an easy fix would be something like:
    function format(string) {   var args = arguments;   var pattern = new RegExp("%([0-9]+)", "g");   return String(string).replace(pattern, function(match, index) {     if (index == 0 || index >= args.length)       throw "Invalid index in format string";     return args[index];   }); };
    (Sorry for nitpicking, I understand it was only an example and brevety is the main objective, but its a great function to have)

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值