I have a collection of users which I just got from a JSON server response. Assume the following:
var users = [
{id: 1, name: 'john', surname: 'smith'},
{id: 2, name: 'john', surname: 'smith'},
{id: 3, name: 'john', surname: 'smith'},
{id: 4, name: 'john', surname: 'smith'},
{id: 5, name: 'john', surname: 'smith'},
{id: 6, name: 'john', surname: 'smith'},
{id: 7, name: 'john', surname: 'smith'}
];
At some points in the business logic and the (handlebars) templates of the application I need to have the full name of each user but of course I don't want to repeat the concatenation logic of name + ' ' + surname
all over the place.
Thus I do the following which "enhances" those users and adds this function I want:
for(var i=0,length=users.length; i<length; i++) {
users[i].getFullName = function() {
return this.name + ' ' + this.surname;
}
}
This technique works fine but my questions are:
- is there a better way of doing this? Note that I want an object oriented style solution and not something like
getFullNameOfUser(user)
. - I can measure the time penalty to add the function to all those objects, but can I measure the memory penalty for adding the function to the objects? Solutions such as JavaScript object size do not count functions.