I wish to create two sets of information that I'm going to re-use, one for a beer and one for a dispenser of beer, in Javascript.
The information is retrieved from an API, and all the beers are objects with an ID, name etc.
I'm wondering if I should bother with making each beer into a function like this:
function Beer() {
this.Id = 0;
this.Name = "";
etc.
}
and then instantiate by setting a variable to a new Beer() through a forEach loop on the parsed JSON string. Is it worth it? Or should I just take the information directly from the API every time I reference different information about each beer? In other words, if this is not the time to use functions as pseudo-classes, when is?
If it helps, I'm writing in MVC, so I'm planning on having the information about the beer and the dispenser in my model, so I can use it with the controller and display it in my view very easily.
CodePudding user response:
For performance, function calls in JavaScript are as cheap as a just set of statements. So it won't affect performance significantly.
For simplicy, if all you need from function Beer
is to copy properties from a JSON, without adding methods. That's simply not necessary. A more convenient way for parsing/normalizing objects from JSON is just apply a mapping function, like:
let objArray = jsonArray.map(json => ({
Id: json.Id || 0,
Name: json.Name
}))