当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JavaScript内置对象:arguments

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 JavaScript内置对象:arguments


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 342 ::
收藏到网摘: n/a

原文:arguments: A JavaScript Oddity. 很不错的文章,推荐一读。我的一点读后感:

arguments是JavaScript里的一个内置对象,和NodeList类似,拥有length属性,但没有push和pop等数组方法。

Dean Edwards的format函数很触发灵感:

function format(string) { var args = arguments;	var pattern = new RegExp('%([1-' + args.length + '])', 'g');	return String(string).replace(pattern, function(match, index) {	return args[index];	});
}
alert(format('%1 want to know whose %2 you %3', 'I', 'shirt', 'wear'));

注意三点:1. String(string)的用法,保证了string为任何值(比如null, false, 123等)时都不会出错。2. 温习下replace方法,第二个参数可以是函数,非常灵活。3. arguments和正则的巧妙配合,实现了format功能。

将arguments转换为真实数组的办法:

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

这个没什么好说的,类数组对象转换为数组都可以采用slice方法。

创建带预置参数的函数:

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))); };
}
var majorTom = makeFunc(format, "This is Major Tom to ground control. I'm %1.");
majorTom("stepping through the door");
majorTom("floating in a most peculiar way");

这个挺有意思的。makeFunc是一个可以创建函数的函数,所创建的函数都带有相同的的预置参数。这能避免代码重复,提高复用性。

创建自引用的函数:

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); } };
}
function comms { alert('s'); }
var somethingWrong = repeat(comms, 3, 2000);
somethingWrong("Can you hear me, major tom?");

其实就是arguments.callee的用法,经常在匿名函数中用来引用自身,这里用来实现repeat函数。注意repeat是一个创建函数的函数,因此有了somethingWrong. 思路有点绕,但想想明白后,很不错。

用原文中的最后一句话来结尾:

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