Kevin Powell - CommunityKP-C
Kevin Powell - Communityโ€ข14mo agoโ€ข
35 replies
Abc

How to avoid duplicate if checks when overriding a method in JavaScript?

I have the following parent class method in JavaScript:

class Parent { jump() { if (!this.isDead()) { this.lastActivityTime = Date.now(); } } isDead() { // returns a boolean } }


In my child class, I'm overriding the jump() method like this:

class Child extends Parent { jump() { if (!super.isDead()) { super.jump(); this.speedY = 30; } } }


I have a duplicate if check for isDead(): once in the parent class and once in the child class. How can I refactor the code to avoid repeating this check, while still maintaining functionality and ensuring the parent method is called correctly?

What is the best practice for handling such situations in JavaScript to make the code cleaner and more maintainable?
Was this page helpful?