Enhance your backend data with ES6 classes
Alexander Nenashev
Posted on April 22, 2024
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.
Posted on April 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.