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

164
Vistas
How to avoid duplicate JS code that each uses its own this?

I have several different classes with the same duplicate code. Aside from the different identity of each's this, these duplicate code are all ostensibly identical.

Here's a simplified example:

class classA {
  ...

  doSomething() {
    if (!this.id || !this.data || !this.isAllowed()) {
      return null;
    }
    return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
  }
}

class classB {
  ...

  doSomething() {
    if (!this.id || !this.data || !this.isAllowed()) {
      return null;
    }
    return someImportedFunc(this.data, this.metadata, this.doSomethingElse());
  }
}

// Many other classes like this

I've thought of moving the doSomething method to another class, then importing it in all these classes. But that would result in a very messy method that takes many, many arguments to account for all the different this's. It'd look like:

class exportedClass {
  function doSomething(id, data, metadata, isAllowed, doSomethingElse) {
    if (!id || !data || !isAllowed()) {
      return null;
    }
    return someImportedFunc(data, metadata, doSomethingElse());
  }
}

class classA {
  ...

  methodThatUsesDoSomething() {
    const result = exportedClass.doSomething(
        this.id, this.data, this.metadata, this.isAllowed, this.doSomethingElse);
    ...
  }
}

Except with like 15 args instead of 5 since this is a simplified example.

How can I avoid duplicate code in this kind of situation?

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

0

Assuming you want a non-inheritance solution, my suggestion would be to pass "this" as an argument, as prototypes can be manipulated as parameters. That would allow you to keep the parameters at a minimum while not losing data.

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