If I have a function like this
function foo (arg1, arg2, callback) {
// blah blah
callback()
}
can I just do:
foo (arg1, arg2)
Sometimes I find that I can't, what's going on here? 开发者_如何学编程Thanks.
the issue is that callback()
will throw an error if you only pass in two arguments since it's effectively doing undefined()
If you are writing the function, you can do:
callback && callback()
meaning that it's only called if it exists (for more of a failsafe, check that it's a function).
If you don't control it, you can pass in an empty function:
foo(arg1, arg2, function(){});
If you don't pass a third parameter to foo, "callback" will have a value of "undefined". Hence, you'll likely hit a script exception when you get to the invocation of the callback() function.
精彩评论