问题
Could you please point me to the nice way of skipping optional parameters in JavaScript.
For example, I want to throw away all opt_ parameters here:
goog.net.XhrIo.send(url, opt_callback, opt_method, opt_content, {\'Cache-Control\': \'no-cache\'}, opt_timeoutInterval)
回答1:
Solution:
goog.net.XhrIo.send(url, undefined, undefined, undefined, {'Cache-Control': 'no-cache'})
You should use undefined instead of optional parameter you want to skip, because this 100% simulates the default value for optional parameters in JavaScript.
Small example:
myfunc(param);
//is equivalent to
myfunc(param, undefined, undefined, undefined);
Strong recommendation: use JSON if you have a lot of parameters, and you can have optional parameters in the middle of the parameters list. Look how this is done in jQuery.
回答2:
Short answer
The safest bet is undefined, and should work almost ubiquitously. Ultimately, though, you cannot trick the function being called into thinking you truly omitted a parameter.
If you find yourself leaning towards using null just because it's shorter, consider declaring a variable named _ as a nice shorthand for undefined:
(function() { // First line of every script file
"use strict";
var _ = undefined; // For shorthand
// ...
aFunction(a, _, c);
// ...
})(); // Last line of every script
Details
First, know that:
typeof undefinedevaluates to"undefined"typeof nullevaluates to"object"
So suppose a function takes an argument that it expects to be of type "number". If you provide null as a value, you're giving it an "object". The semantics are off.1
As developers continue to write increasingly robust javascript code, there's an increasing chance that the functions you call explicitly check a parameter's value for undefined as opposed to the classic if (aParam) {...}. You'll be on shaky ground if you continue to use null interchangeably with undefined just because they both happen to coerce to false.
Be aware, though, that it is in fact possible for a function to tell if a parameter was actually omitted (versus being set to undefined):
f(undefined); // Second param omitted
function f(a, b) {
// Both a and b will evaluate to undefined when used in an expression
console.log(a); // undefined
console.log(b); // undefined
// But...
console.log("0" in arguments); // true
console.log("1" in arguments); // false
}
Footnotes
- While
undefinedalso isn't of type"number", it's whole job is to be a type that isn't really a type. That's why it's the value assumed by uninitialized variables, and the default return value for functions.
回答3:
Just pass null as parameter value.
Added: you also can skip all consequent optional parameters after the last that you want to pass real value (in this case you may skip opt_timeoutInterval parameter at all)
来源:https://stackoverflow.com/questions/8356227/skipping-optional-function-parameters-in-javascript