Is it possible to cancel object creation in coffeescript if certain criteria are not met? I want to do something like this:
class Foo
constructor:(@name) ->
return false if !name
withName = new Foo("bar") #withName -> obj
noName = new Foo #noName -> false
But with that code the object is still created. What is the best way to do this?
You need to check the validation conditions at the call site, inside the constructor is far to late.
Take a look at the compiled javascript for the class:
And it should be a little more clear why it doesn’t work.
The
newkeyword happens before the constructor is called.How about something like this (NOT TESTED)
Which compiles down to: