[英]How can I deal with optional parameters in JavaScript?
I would like a function 'get' that takes an id, an optional property parameter and a callback function. 我想要一个带有id,可选属性参数和回调函数的函数'get'。 It would be used like so:
它会像这样使用:
get(14297, 'name', function processName(name) {...});
get(14297, function processStudent(student) {...});
I have included one possible implementation below 我在下面列出了一个可能的实现
function get(id, property, callback) {
var item = ...;
// property is callback
if (!callback) property(item);
// callback is callback
else callback(item[property])
}
It feels a little bit weird because 感觉有点奇怪,因为
property(item);
Is actually a callback function depending on the context. 实际上是一个取决于上下文的回调函数。 Is there a better way to do this?
有一个更好的方法吗?
You should switch the parameters. 你应该切换参数。 Try this
尝试这个
function get(id, callback, property)
{
if(typeof property === "undefined")
callback(item);
else
callback(item[property]);
}
This is the pattern used by jQuery: 这是jQuery使用的模式:
function get(id, property, callback) {
// if the 2nd parameter is a function, assume that
// only two parameters were supplied
if (typeof property === 'function') {
callback = property;
property = undefined;
}
...
}
Effectively, if it sees unexpected parameter types it just shuffles their contents around until they match the alternative definition. 实际上,如果它看到意外的参数类型,它只是将它们的内容混洗,直到它们与替代定义匹配。
You can change the order of parameters, or test what the function is given to work out what they are. 您可以更改参数的顺序,或测试给出的功能以确定它们的含义。 eg
例如
function get(id, property, callback) {
if (arguments.length == 2) {
// second argument is callback
callback = property;
property = void 0;
}
...
}
or 要么
function get(id, property, callback) {
if (typeof property == 'function') {
// second argument is callback
callback = property;
property = void 0;
}
...
}
and so on, but that type of overloading is not particularly liked. 等等,但这种类型的重载并不是特别受欢迎。
The arguments
object is immutable. arguments
对象是不可变的。 But you can slice it in an array, pop the last argument and deal with the other arguments as you normally would, since you know the callback
argument isn't in it anymore. 但是你可以在数组中对它进行切片,弹出最后一个参数并像往常一样处理其他参数,因为你知道
callback
参数不再存在于其中。
Here is a way to do this: 这是一种方法:
function get() {
// Copy the `arguments` object in an array, since it's immutable
var args = Array.prototype.slice.call( arguments, 1 ),
// Pop the last argument of the arguments
callback = args.pop();
// Then deal with other arguments
// For example, check for the existence of the second argument
if ( args[1] ) {
}
// Then, you can call the callback function
callback();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.