Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!