Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

174
Vistas
How to rewrite class to plain object?

How would one rewrite this class to a plain object?

class ExampleClass {
    firstPropery: number = 0;
    secondProperty!: string;

  async exampleMethod(): Promise<void> {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    this.secondProperty = secondProperty;
  }
}

I would think it's something similar as this

interface IExample {
  firstProperty: number;
  secondProperty: string;
  exampleMethod: () => Promise<void>;
}

const Example: IExample = {
  firstProperty: 0,
  exampleMethod: async (): Promise<void> => {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    ...
  }
}

But how to set the secondProperty via the exampleMethod? In the class method I can just write this.secondProperty = ..., which I cannot do in the plain object.

My second question is, with the class I would make a new object like this const newObject = new ExampleClass();. With the plain object way, how would I make a new object instance?

Any help is gladly appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In the class method I can just write this.secondProperty = ..., which I cannot do in the plain object.

Actually you can. It doesn't matter whether it's defined in a class or object literal, exampleMethod is still a method and when called as example.exampleMethod() it will have its this point to example. However, you cannot use an arrow function to define it - use method syntax instead:

const example: IExample = {
  firstProperty: 0,
  async exampleMethod(): Promise<void> {
    const { secondProperty } = await SomeHelperClass.exampleRequest();
    ...
  }
}

With the class I would make a new object like this const newObject = new ExampleClass();. With the plain object way, how would I make a new object instance?

You write the code again and again. Or you use Object.assign to copy the method onto a new object. Or you place the object literal inside a function that you can call multiple times.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda