I'd get rid of the json
function. Having it means you have to remember to use somePerson.json()
instead of the usual JSON.stringify(somePerson)
. If you need to control the JSON output to make sure your API stays the same even as your class changes, you can do that using a toJSON
function - JSON.stringify
will respect such a function if it exists. And you have a perfectly fine toJSON
function already - you just called it returnObject
instead.
Though speaking of returnObject
, it doesn't seem very useful in its current state. You take an object, and return an object that contain all the first object's fields. At that point, why not just return the first object itself? And once you have a function that essentially just reads return this
, why have that function at all? You can't call the function without already having access to its return value anyway, right?
Granted, having it does serve to freeze the output of json
(or, if you were to use this function as your toJSON
, the output of JSON.stringify
), which might help you avoid accidentally changing your API.
All in all, I'd probably suggest simplifying to
class Person {
constructor(firstName, lastName, email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}
though if you want to be sure you don't accidentally change your JSON output by changing the class (and you don't trust your test to notice if you do) you might prefer
class Person {
constructor(firstName, lastName, email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
toJSON() {
return {
"firstName": this.firstName,
"lastName": this.lastName,
"email": this.email
};
}
}