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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay