通读一遍this http://jashkenas.github.com/coffee-script/,我谈到了函数参数的默认值:
fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
这很简洁,但后来我尝试了这个:
fill = (container="mug", liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
alert fill(liquid="juice")
并得到了意外的警报"Filling the juice with coffee..."
。然后我尝试了这个:
fill = (container="mug", liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
alert fill(null, "juice")
它起作用了。但它并不漂亮。有没有更好的方法,或者这是执行此操作的惯用方法?
fill = ({container, liquid} = {}) ->
container ?= "mug"
liquid ?= "coffee"
"Filling the #{container} with #{liquid}..."
alert fill(liquid: "juice", container: "glass")
alert fill()
fill = (quantity="500 mL", {container, liquid} = {}) ->
container ?= "mug"
liquid ?= "coffee"
"Filling the #{container} with #{quantity} of #{liquid}..."
alert fill("1L", liquid: "juice", container: "glass")
alert fill()
alert fill "1L"
alert fill "1L", liquid: "water"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)