Default function parameter ordering

后端 未结 3 385
旧时难觅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:16

    Amir and Jeremy already have this. As they point out, container="mug" in a function's argument list is really just shorthand for container ?= "mug" in the function body.

    Let me just add that when calling functions,

    fill(liquid="juice")
    

    means the same thing as in JavaScript: First, assign the value "juice" to the liquid variable; then pass liquid along to fill. CoffeeScript doesn't do anything special here, and liquid has the same scope in that situation as it would outside of the function call.

    By the way, I've suggested that the default argument syntax should be made more powerful by allowing arguments to be skipped (e.g. (first, middle ?= null, last) -> would assign values to first and last if only two arguments were passed), and that the ?= syntax should be used rather than =. You might want to express support for that proposal here: issue 1091.

提交回复
热议问题