Reputation: 4732
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?
Upvotes: 0
Views: 440
Reputation: 77416
The only way to do this is to throw an exception from the constructor:
class Foo
constructor:(@name) ->
throw new Error('Name must be specified') if !name
However, as a stylistic matter, exceptions aren't commonly used this way in JS.
Upvotes: 4
Reputation: 17808
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:
Foo = (function() {
function Foo(name) {
this.name = name;
if (!name) return false;
}
return Foo;
})();
withName = new Foo("bar");
noName = new Foo;
}).call(this);
And it should be a little more clear why it doesn't work.
The new
keyword happens before the constructor is called.
How about something like this (NOT TESTED)
runIf = (someVar, someDelegate) ->
someDelegate someVar if someVar
withName = runIf "bar", -> new Foo("bar")
noName = runIf null, -> new Foo()
Which compiles down to:
runIf = function(someVar, someDelegate) {
if (someVar) return someDelegate(someVar);
};
withName = runIf("bar", function() {
return new Foo("bar");
});
noName = runIf(null, function() {
return new Foo();
});
Upvotes: 2