jashkenas/coffee-script — Issue #1893: Default values for constructors not available immediately?
Author: ilazarte
Created: 2011-11-25 20:04:43+00:00
State: open

This violates the rule of least surprise to me, although admittedly I'm new to coffeescript. For functions, default args are available immediately, as the sample function below shows the difference. The constructor version works correctly if its an @ reference, but not if you use the passed in parameter. Should it behave more like the function version? In that case the compiled version should do an undefined check an create a value for baz in the case below.

code:
class samplecls
constructor:(@foo, @bar, @baz = "drinking") ->
console.log "[cls] i was #{@foo} at #{@bar} while #{@baz}"
console.log "[cls] i was #{foo} at #{bar} while #{baz}"

samplefn = (foo, bar, baz = "drinking") ->
console.log "[fn] i was #{foo} at #{bar} while #{baz}"

new samplecls "Relaxing", "Harry's"
samplefn "Relaxing", "Harry's"

output:
[cls] i was Relaxing at Harry's while drinking
[cls] i was Relaxing at Harry's while undefined
[fn] i was Relaxing at Harry's while drinking