In JavaScript you can make a function like this:
function Cat(children) {
this.children = children || 3;
}
What it does is that it creates a Cat
object with a children
value, if you do not pass the children
inside the function like var mimmi = new Cat();
, it will be the same as var mimmi = new Cat(undefined);
, which means that mimmi
will have the default amount of children
which is 3.
However, the only problem with this is that if I enter 0
, it will be count as false
and children
will be set to 3
, when I actually want it to be set to 0
.
What's the most elegant way to make a function like this but still allow for 0's?
I don't really think this is so nice looking though:
function Cat(children) {
this.children = (typeof this.children == "number") ? children : 3
}