在 javascript 中,只有一个函数具有任何给定名称,如果声明了多个具有相同名称的函数,则最后声明的函数将是活动的。
但是,您可以测试传递给您的函数的参数并实现许多与函数重载旨在处理的相同类型的行为。事实上,在某些情况下,您可以做得更多。
在您的具体示例中:
function abc(s, t) {
// test to see if the t argument was passed
if (t !== undefined) {
console.log('was called as abc(s,t)');
} else {
console.log('was called as abc(s)');
}
}
abc('1'); // outputs 'was called as abc(s)'
abc('1', '2'); // outputs 'was called as abc(s,t)'
但是,您还可以获得更多、更多的创意(并且有用)。
例如,jQuery .css() 方法可以有五种不同的调用方式。
.css( propertyName )
.css( propertyNames )
.css( propertyName, value )
.css( propertyName, function(index, value) )
.css( properties )
.css() 方法中的代码检查参数的类型和数量,以确定调用它的方式,从而确定要执行的操作。
让我们看看如何做到这一点,以确定正在使用该函数的 5 种形式中的哪一种:
css: function(prop, value) {
// first figure out if we only have one argument
if (value === undefined) {
if (typeof prop === "string") {
// we have a simple request for a single css property by string name
// of this form: .css( propertyName )
} else if (Array.isArray(prop)) {
// we have a request for an array of properties
// of this form: .css( propertyNames )
} else if (typeof prop === "object") {
// property-value pairs of css to set
// of this form: .css( properties )
}
} else {
if (typeof value === "function") {
// of this form: .css( propertyName, function(index, value) )
} else {
// of this form: .css( propertyName, value )
}
}
}
您还可以实现可选参数。例如,jQuery 的.hide() 可以接受多种形式。其中一种形式是.hide( [duration ] [, complete ] ),其中持续时间和完成功能都是可选的。您可以不传递任何内容,只传递一个持续时间或同时传递一个持续时间和完成回调函数。可以这样实现:
hide: function(duration, fn) {
// default the duration to zero if not present
duration = duration || 0;
// default the completion function to a dummy function if not present
fn = fn || function() {};
// now the code can proceed knowing that there are valid arguments for both
// duration and fn whether they were originally passed or not
}
我发现使用这些变量参数最有用的方法之一是允许代码支持各种不同的参数类型,这样无论你的参数处于什么状态,你都可以直接传递它们,而无需将它们转换为某种通用类型。例如,在 javascript 中的 this implementation of a set object 中,.add() 方法可以采用所有这些不同形式的参数:
s.add(key)
s.add(key1, key2, key3)
s.add([key1, key2, key3])
s.add(key1, [key8, key9], key2, [key4, key5])
s.add(otherSet) // any other set object
s.add(arrayLikeObject) // such as an HTMLCollection or nodeList
这两者都接受可变数量的参数,并且它接受每个参数的许多不同类型,并且它将根据传递给它的内容进行调整。因此,您可以通过键列表、键数组、另一个集合、伪数组或这些类型的任何混合来初始化一个集合。在内部,代码只是遍历传递给函数的每个参数,检查参数的类型并采取相应的行动。
您可以查看代码here on GitHub 以了解有关如何完成此操作的更多信息。