DEV Community

Alexander Nenashev
Alexander Nenashev

Posted on • Edited on

2

Enhance your backend data with ES6 classes

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}`;
  }
}
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
oculus42 profile image
Samuel Rouse

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!

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay