- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
JavaScript Overriding Method: Syntax, Usage, and Examples
In JavaScript, overriding a method means redefining a method from a superclass in a subclass. This allows child classes to modify or extend the behavior of inherited methods.
How to Use JavaScript Overriding Method
To override a method in JavaScript, create a method in the subclass with the same name and parameter list as the one in the superclass. JavaScript will automatically use the subclass method when it's called on an instance of that subclass.
class Human {
receiveDamage() {
console.log("Took 10 damage.");
}
}
class Wizard extends Human {
receiveDamage() {
console.log("Took only 5 magic damage.");
}
}
In this example, Wizard
overrides the receiveDamage()
method from Human
. Calling receiveDamage()
on a wizard instance will use the wizard's version.
When to Use JavaScript Overriding Method
Overriding is useful when different object types need slightly different behaviors for the same operation. Here are three common cases:
1. Customizing inherited behavior
If a subclass should act differently from its parent class, override the relevant method to change the behavior.
2. Extending functionality
Sometimes the subclass needs to do what the parent does, and then something extra. You can override the method and still call the original with super
.
3. Simplifying polymorphism
Overriding supports polymorphism, where the same method name can behave differently based on the object’s class.
Examples of JavaScript Overriding Method
Example 1: Different subclasses handle damage differently
class Human {
constructor() {
this.health = 100;
}
receiveDamage() {
this.health -= 10;
console.log(`Health is now ${this.health}`);
}
}
class Wizard extends Human {
receiveDamage() {
this.health -= 5;
console.log(`Wizard uses magic barrier. Health is now ${this.health}`);
}
}
const wizard = new Wizard();
wizard.receiveDamage(); // Outputs: Wizard uses magic barrier. Health is now 95
Example 2: Overriding and calling the original method
class Vehicle {
start() {
console.log("Starting engine...");
}
}
class ElectricCar extends Vehicle {
start() {
super.start();
console.log("Checking battery charge.");
}
}
const car = new ElectricCar();
car.start();
// Outputs:
// Starting engine...
// Checking battery charge.
Example 3: Creating different greetings
class Person {
greet() {
console.log("Hello!");
}
}
class Developer extends Person {
greet() {
console.log("Hey, I write code.");
}
}
const dev = new Developer();
dev.greet(); // Outputs: Hey, I write code.
Learn More About JavaScript Overriding Method
How to override a method in JavaScript using super
If your overridden method still needs the functionality of the original, use super.methodName()
to call it from the subclass.
class Character {
speak() {
console.log("The character speaks.");
}
}
class Villager extends Character {
speak() {
super.speak();
console.log("Welcome to our town.");
}
}
Using super
is helpful for layering behavior rather than completely replacing it.
Overriding in prototype-based syntax
Before ES6 classes, JavaScript used constructor functions with prototypes. You can still override methods in this style.
function Animal() {}
Animal.prototype.makeSound = function () {
console.log("Some sound");
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.makeSound = function () {
console.log("Woof!");
};
const pup = new Dog();
pup.makeSound(); // Outputs: Woof
JavaScript overriding method vs. method overloading
JavaScript doesn’t support method overloading (multiple methods with the same name but different parameter lists). If two methods with the same name exist in the same class, the last one defined overrides the previous one.
class Example {
greet() {
console.log("Hi there!");
}
// This overrides the previous greet
greet(name) {
console.log(`Hi, ${name}!`);
}
}
const e = new Example();
e.greet("Jesse"); // Outputs: Hi, Jesse!
To mimic overloading, use optional parameters or argument checks:
class Greeter {
greet(name) {
if (name) {
console.log(`Hello, ${name}`);
} else {
console.log("Hello there!");
}
}
}
Best practices for overriding
- Keep the method signature identical to avoid unexpected behavior.
- Only override when necessary to modify logic.
- Use
super
when you need to build on top of existing behavior. - Comment your code to explain why the method is being overridden.
The JavaScript overriding method pattern is a fundamental technique in object-oriented programming. It lets subclasses offer their own version of inherited methods. Whether you're customizing how a wizard handles damage, how a form behaves on submit, or how different characters speak in a game, overriding gives you the control you need.
Once you understand how to override a method in JavaScript, you unlock a powerful tool for building flexible, reusable, and expressive code.