1

I have been seeing functions with signatures

some_fn arg1, arg2, [optional], cb

How is this done?

2
  • Where have you seen this? Usually, the optional arguments go at the very end. Commented Jun 13, 2013 at 18:07
  • In this example, which parameters should be optional, and which ones should be mandatory? Commented Jun 13, 2013 at 18:26

1 Answer 1

2

jQuery does that sort of thing all the time, on for example:

.on( events [, selector ] [, data ], handler(eventObject) )

The way it works is that the inner optional arguments and the final argument have different types so the function can parse arguments by hand using typeof (or similar but looser checks like the various is* functions in Underscore) to figure out how it was called. If there are multiple things in the possible argument list that are the same type then you'd throw a length check into the mix to try and figure out what the intent is.

For example:

f = () ->
    args = Array::slice.apply(arguments)
    if(typeof args[0] == 'function')
        args[0]()
    else
        console.log("#{args[0]} is not a function")

f(1, 2, 3)
f(-> console.log('pancakes'))

Demo: http://jsfiddle.net/ambiguous/c6UwC/

A more CoffeeScript-ish version would use ... instead of dealing with arguments directly:

f = (args...) ->
    if(typeof args[0] == 'function')
        args[0]()
    else
        console.log("#{args[0]} is not a function")

Demo: http://jsfiddle.net/ambiguous/gPmJZ/

Sign up to request clarification or add additional context in comments.

3 Comments

aww interesting use of the splat
@Alexis: As far as why this argument form is used, putting an anonymous function in the middle of an argument list is pretty ugly and visually confusing (yes setTimeout and setInterval do it but those signatures are (IMO) mistakes and lead to lots of nasty looking code).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.