Murakami
Murakami

Reputation: 3760

Shared logic between constructor and another function in Java Script

I have a situation like that:

class TestClass {
   constructor() {
    shared logic
  }

  anotherFunction() {
    shared logic
  }
}

How can I achieve that not duplicating the code?

Upvotes: 0

Views: 83

Answers (2)

Matus Dubrava
Matus Dubrava

Reputation: 14462

As always, create a function for the shared logic, either inside of the class or outside of it.

class TestClass {
    constructor() {
        this.sharedLogicFunction();
    }

    anotherFunction() {
        this.sharedLogicFunction();
    }

    sharedLogicFunction() {}
}

Upvotes: 2

sbqq
sbqq

Reputation: 1091

Put your code to the anotherFunction() and call this function from constructor.

class TestClass {
   constructor() {
    this.anotherFunction();
  }

  anotherFunction() {
    here is some logic to do
  }
}

Upvotes: 0

Related Questions