Currently, I have a function defined like:
function a(b,c) {
if (typeof(b) === "undefined") { b = 1; }
if (typeof(c) === "undefined") { c = 2; }
...
}
Before, it set to default if the value was falsy. Changing this breaks the following call:
a(null, 3);
There is no undefined object. How can I pass only the second argument?
There is, actually, an undefined object:
There may be an undefined object normally, but clearly in my environment something has gone awry
Currently, I have a function defined like:
function a(b,c) {
if (typeof(b) === "undefined") { b = 1; }
if (typeof(c) === "undefined") { c = 2; }
...
}
Before, it set to default if the value was falsy. Changing this breaks the following call:
a(null, 3);
There is no undefined object. How can I pass only the second argument?
There is, actually, an undefined object:
There may be an undefined object normally, but clearly in my environment something has gone awry
Share Improve this question edited Jan 12, 2013 at 4:26 cacba asked Jan 12, 2013 at 4:15 cacbacacba 4134 silver badges9 bronze badges3 Answers
Reset to default 4There is, actually, an undefined
object:
a(undefined, 3);
It, is, however, for some reason, a variable, so someone could do :
undefined = 2;
Your code wouldn't work any more. If you want to protect yourself against someone redefining undefined
, you can do this:
a(void 0 /* zero's not special; any value will do */, 3);
The void
prefix operator takes a value, discards it, and returns undefined
.
A good test for checking the existence of a variable is this:
(typeof b === "undefined" || b === null)
Thus, your function can be rewritten like this :
function a(b,c) {
if (typeof(b) === "undefined" || b === null) { b = 1; }
if (typeof(c) === "undefined" || b === null) { c = 2; }
...
}
This would account for any of undefined
, null
or void 0
passed as arguments. If you find that repetitive, you can always define a utility function :
function exists(obj) {
return typeof(obj) === "undefined" || obj === null;
}
And this precise test is what Coffee-script does with its existential operator ?
. Coffee-script offers default arguments as well, which would make your life even easier.
not sure why you say there's no undefined...
a(undefined, 3)
is what you want
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744307756a4567800.html
评论列表(0条)