我有一个函数
function callback(obj){...}
可以传入比函数签名中声明的更多的对象吗?例如,这样叫它:
callback(theObject, extraParam);
我在Firefox上试过了,似乎没有问题,但这样做不好吗?
发布于 2010-03-27 01:58:59
JavaScript允许这样做,你可以向一个函数传递任意数量的参数。
它们可以在arguments
对象中访问,该对象是一个类似数组的对象,具有包含调用函数时使用的参数值的数值属性、一个告诉您调用中使用了多少个参数的length
属性以及一个引用函数本身的callee
属性,例如,您可以这样写:
function sum(/*arg1, arg2, ... , argN */) { // no arguments defined
var i, result = 0;
for (i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
sum(1, 2, 3, 4); // 10
数组对象可能看起来像一个数组,但它是一个继承自Object.prototype
的普通对象,但如果要对其使用arguments
方法,则可以直接从Array.prototype
调用它们,例如,获取实际数组的常见模式是使用slice
方法:
function test () {
var args = Array.prototype.slice.call(arguments);
return args.join(" ");
}
test("hello", "world"); // "hello world"
此外,使用function对象的length
属性,还可以知道函数需要多少个参数:
function test (one, two, three) {
// ...
}
test.length; // 3
发布于 2010-03-27 02:08:01
是的,这样做--这是一个很好的实践,而且是一个强大的JavaScript特性
https://stackoverflow.com/questions/2525568
复制相似问题