A traditional way of handling backend data on a frontend is to feed it to services, controllers, components and the like. But when I started binding ES6 classes to backend data and all business logic went into classes, my components got much cleaner, and I got a lot of possibilities to handle and transform data inside classes. It was a big shift to make my frontend code cleaner and shorter. You just simply use Object.setPrototypeOf
:
classes.mjs
export class User{
get fullName(){
return `${this.firstName} ${this.lastName}`;
}
}
import { User } from './classes.mjs';
// fetch some users then attach the class
users.forEach(user => Object.setPrototypeOf(user, User.prototype));
// now you can use `user.fullName` anywhere
Another reason to bind class prototypes is performance. You don't need to create a new copy of data consisting of class instances, copy data into instance properties and so on and thus you save precious CPU time and memory providing faster user experience.
Top comments (1)
Thanks for the interesting perspective!
I mostly lean toward utility libraries and composing functional operations, but I can see how attaching a prototype provides a lot of convenience for deriving data, especially with getters!