0

I have a situation like that:

class TestClass {
   constructor() {
    shared logic
  }

  anotherFunction() {
    shared logic
  }
}

How can I achieve that not duplicating the code?

1
  • 4
    Huh... put the logic within anotherFunction and call it from the constructor? Commented Nov 30, 2018 at 16:33

2 Answers 2

2

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() {}
}

Sign up to request clarification or add additional context in comments.

2 Comments

This looks exactly right! Note that the ONLY restriction here is that super must be called before this is referenced. If for some weird reason sharedLogicFunction needs to occur before a call to super, sharedLogicFunction would need to be made static or defined outside the class altogether.
But isn't it like that super needs to be called in order to access parent class, ie. when child class extends parent? Then we would have access to parents methods. In the scenario above is it really necassacy to call super in order to use 'this'?
0

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.