Javascript default arguments, only passing the second - Stack Overflow

Currently, I have a function defined like:function a(b,c) {if (typeof(b) === "undefined") { b

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 badges
Add a ment  | 

3 Answers 3

Reset to default 4

There 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

相关推荐

  • Javascript default arguments, only passing the second - Stack Overflow

    Currently, I have a function defined like:function a(b,c) {if (typeof(b) === "undefined") { b

    7天前
    60

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信