Page 21 - JavaScript修炼之道
P. 21
任务3 使用可选/可变/命名参数 7
声明参数(命名参数)
function repeat(rant, times) {
while (--times >= 0)
alert(rant);
}
repeat('IE6 must die!', 5); // => 连续弹出5个对话框
动态获得不定数量的参数
内置的arguments变量允许你动态访问函数的参数。
这使你可以模拟其他语言中的变长参数列表,比如C语言的varargs。
function repeat(times) {
while (--times >= 0) {
for (var index = 1, len = arguments.length; index < len; ++index) {
alert(arguments[index]);
}
}
}
repeat(2, 'IE6 must die!', 'So should IE7...'); // => 连续弹出4个对话框
为可选参数设置默认值
function repeat(times, rant) {
if (undefined === rant) {
rant = 'IE6 must die!';
}
while(--times >= 0) {
alert(rant);
}
}
repeat(3); // => 连续弹出3个有关IE6的对话框
repeat(3, 'So should IE7...'); // => 连续弹出3个有关IE7的对话框
用字面量对象实现伪命名参数
function repeat(options) {
options = options || {};
for (var opt in (repeat.defaultOptions || {})) {
if (!(opt in options)) {
options[opt] = repeat.defaultOptions[opt];
}
}
for (var index = 0; index < options.times; ++index) {
alert(options.rant);
}
}
repeat.defaultOptions = { times: 2, rant : 'IE6 must die!' };
repeat(); // 弹出两个与IE6有关的对话框
repeat({ times: 3 }); // 弹出3个与IE6有关的对话框
repeat({ times: 2, rant: 'Flash must die!' }); // 弹出两个与Flash有关的对话框