在javascript中处理可选参数 [英] Handling optional parameters in javascript
问题描述
我有一个静态javascript函数,可以使用1,2或3个参数:
I have a static javascript function that can take 1, 2 or 3 parameters:
function getData(id, parameters, callback) //parameters (associative array) and callback (function) are optional
我知道我可以随时测试给定参数是否未定义,但我怎么知道传递的是参数还是回调?
I know I can always test if a given parameter is undefined, but how would I know if what was passed was the parameter or the callback?
这样做的最佳方法是什么?
What's the best way of doing this?
可以传递的内容示例:
1:
getData('offers');
2:
var array = new Array();
array['type']='lalal';
getData('offers',array);
3:
var foo = function (){...}
getData('offers',foo);
4:
getData('offers',array,foo);
推荐答案
你可以知道有多少参数被传递给您的函数,您可以检查您的第二个参数是否是函数:
You can know how many arguments were passed to your function and you can check if your second argument is a function or not:
function getData (id, parameters, callback) {
if (arguments.length == 2) { // if only two arguments were supplied
if (Object.prototype.toString.call(parameters) == "[object Function]") {
callback = parameters;
}
}
//...
}
你也可以这样使用arguments对象:
You can also use the arguments object in this way:
function getData (/*id, parameters, callback*/) {
var id = arguments[0], parameters, callback;
if (arguments.length == 2) { // only two arguments supplied
if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
callback = arguments[1]; // if is a function, set as 'callback'
} else {
parameters = arguments[1]; // if not a function, set as 'parameters'
}
} else if (arguments.length == 3) { // three arguments supplied
parameters = arguments[1];
callback = arguments[2];
}
//...
}
如果你有兴趣的,请看看John Resig的这篇文章,了解一种模拟技术JavaScript上的方法重载。
If you are interested, give a look to this article by John Resig, about a technique to simulate method overloading on JavaScript.
这篇关于在javascript中处理可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!