I have a few questions regarding the code below:
export class Person {
constructor(obj = { id: 0, name: '', lastName: '', eyeColor: '', age: 0 }) {
this.id = obj.id;
this.name = obj.name;
this.lastName = obj.lastName;
this.eyeColor = obj.eyeColor;
this.age = obj.age;
}
yearOfBirth() {
return new Date().getFullYear() - this.age;
}
json() {
return JSON.stringify(this);
}
}
FWIW: I prefer to create an object using this syntax:
let newPerson = new Person(
{
id: 0,
name: "Werner",
lastName: "Venter",
age: 37
}
);
I really dislike this way:
let newPerson = new Person(0, "Werner", "Venter", 37);
It just reads easier for me when I have the parameter name with the value. Anyway, I digress…
- Is this the correct/accepted way to create an object class? I will be using it to receive data from an API that sends it in this format as JSON.
- How do I make a parameter optional? Mainly why I need this is that the ID value is not required when creating a new entry on the API, so I would prefer not to include the ID value when creating the object.
- Finally, do you have any opinion/advice on this approach?
Thank you in advance guys. Really appreciate this community.