asfman
android developer
posts - 90,  comments - 213,  trackbacks - 0

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:


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

view plain | print
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:


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

view plain | print
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:


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

view plain | print
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:


1 function makeFunc() { 
2   var args = Array.prototype.slice.call(arguments); 
3   var func = args.shift(); 
4   return function() { 
5     return func.apply(null, args.concat(Array.prototype.slice.call(arguments))); 
6   }; 
7

view plain | print
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.

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:


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

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

You can call the majorTom function repeatedly like this:


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

view plain | print
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:


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

view plain | print
"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:


1 function repeat(fn, times, delay) { 
2   return function() { 
3     if(times-- > 0) { 
4       fn.apply(null, arguments); 
5       var args = Array.prototype.slice.call(arguments); 
6       var self = arguments.callee; 
7       setTimeout(function(){self.apply(null,args)}, delay); 
8     } 
9   }; 
10

view plain | print
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:


1 function comms(s) { 
2   alert(s); 
3

view plain | print
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:


1 var somethingWrong = repeat(comms, 3, 2000); 
2  
3 somethingWrong("Can you hear me, major tom?"); 

view plain | print
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!

posted on 2009-01-14 16:29 汪杰 阅读(203) 评论(0)  编辑 收藏 引用 所属分类: javascript
只有注册用户登录后才能发表评论。

<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

常用链接

留言簿(15)

随笔分类(1)

随笔档案(90)

文章分类(727)

文章档案(712)

相册

收藏夹

http://blog.csdn.net/prodigynonsense

友情链接

最新随笔

搜索

  •  

积分与排名

  • 积分 - 466814
  • 排名 - 6

最新随笔

最新评论

阅读排行榜

评论排行榜