Hello. There is some constructor.
var Animal = function (data) { this.name = data.name; this.age = data.age; this.kind = data.kind; } It is necessary to validate the input data. That is, make sure that typeof name === String , typeof age === 'number' and 1+['cat', 'dog', 'mongoose'].indexOf(kind) . How to check this is obvious. The question is where to check. Right in the constructor? Or so:
var validate = function () { if (typeof this.name !== 'string') throw new Error; if (typeof this.age !== 'number') throw new Error; if (-1 === ['cat', 'dog', 'mongoose'].indexOf(kind)) throw new Error; }, Animal = function (data) { this.name = data.name; this.age = data.age; this.kind = data.kind; validate.call(this); } How to do it right?
@eicto
the difference in my and your code is also this - I first validate and then initialize
Animal = function (data) { validate.call(this); this.name = data.name; this.age = data.age; this.kind = data.kind; } The fact that the validation takes place in the designer is already considered a sign of gavnokod?
@Etki,
But if you do not strive to write the perfect code right away - well, uh, this is sad.
Well, why would I raise this question at all if I didn’t try to write normal code initially))?