Default function parameter ordering

后端 未结 3 351
旧时难觅i
旧时难觅i 2021-01-30 08:28

Reading through this, I came to the bit on default values for function arguments:

fill = (container, liquid = \"coffee\") ->
  \"Filling the #{container} with         


        
3条回答
  •  后悔当初
    2021-01-30 09:28

    Currently, there's no way to call with named arguments. It would require knowing the arguments (names, positions, and/or default values) at the calling site, which is not always feasible in javascript/coffeescript.

    Instead if you have many arguments and you want to name them and have default values, you could do something like this:

    fill = (opts = {}) ->
        opts.container ?= "mug"
        opts.liquid ?= "coffee"
        "Filling the #{opts.container} with #{opts.liquid}..."
    
    alert fill
        liquid:"juice"
        container:"cup"
    
    alert fill
        liquid:"juice"
    
    alert fill()
    

提交回复
热议问题