JavaScript内置对像arguments介绍

黄舟
黄舟 原创
2016-12-15 10:46:45 1037浏览

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!

以上就是JavaScript内置对像arguments介绍的内容,更多相关文章请关注PHP中文网(m.sbmmt.com)!


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。