If I have a function
foo()
that I call with no arguments most of the time, but one argument in special cases, is
var arg1 = arguments[0];
if (arg1) {
开发者_JAVA技巧 <special case code>
}
inside the function a completely safe thing to do?
Yes it is safe. Unless you pass in false
, ""
, 0
, null
or undefined
as an argument. It's better to check againts the value of undefined
. (If you pass in undefined
then tough! that's not a valid argument).
There are 3 popular checks
foo === undefined
: Standard check but someone (evil) might dowindow.undefined = true
typeof foo !== "undefined"
: Checks for type and is safe.foo === void 0
:void 0
returns the realundefined
But this is prefered
function myFunction(foo) {
if (foo !== undefined) {
...
} else {
...
}
}
Yes, that's fine. A reasonable alternative is to name the argument, and not use the arguments
object:
function foo(specialArg)
{
if (specialArg)
{
// special case code
}
}
Note that if(bar)
tests the truthiness of bar
. If you call foo
with any falsy value, such asfoo(0)
, foo(false)
, foo(null)
, etc., the special case code will not execute in the above function (or your original function, for that matter). You can change the test to
if (typeof specialArg !=== 'undefined')
{
// ...
}
to make sure that the special case code is executed when the argument is supplied but falsy.
You can do this:
function foo(arg1){
if (arg1){
// Special case
}
else{
// No argument
}
// Rest of function
}
As long as you document the behaviour sufficiently I don't see anything wrong with it.
However you'd be better off checking the argument length, as opposed to how you're doing it now. Say for example you called:
myFunction(0);
It will never process the argument.
If it's a single optional argument you may be better off having it as a named argument in the function and checking if a defined value was passed in, depends on your use case.
The basic fact you are interested in is "was foo called with 0 or 1 argument(s)?". So I would test arguments.length
to avoid future problems with a special argument that evaluates to false.
精彩评论