79298876

Date: 2024-12-21 04:36:25
Score: 3
Natty:
Report link

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.

Yes, you have created a class which handles some properties of an object, in this way you must pass a class to the constructor. (because you've used statements such as obj.name)

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.

You just did, by declaring obj = <some_object>, note that by what you did here, in case no object will be passed when you create a new instance of Person, the default object you have provided will be used as a default value.

let newPerson = new Person(0, "Werner", "Venter", 37);

This one is wrong btw, your constructor method excepts one parameter while in the example above 4 are provided.

This way is the correct one indeed (but it drag an error because eyeColor was not provided):

let newPerson = new Person( { id: 0, name: "Werner", lastName: "Venter", age: 37 } );

Reasons:
  • Blacklisted phrase (1): How do I
  • Blacklisted phrase (0.5): I need
  • Long answer (-1):
  • No code block (0.5):
  • Contains question mark (0.5):
  • Starts with a question (0.5): Is this the
  • Low reputation (1):
Posted by: Yuval Jacobson