This post will describe the process for overriding a function in JavaScript.
How to Override a Function in JavaScript?
In JavaScript, the following functions can be overridden
- the JavaScript Predefined methods
- the User-defined function
- Parent class functions/methods
How to Override the JavaScript Predefined Methods?
In JavaScript, the predefined methods will also be overridden. For overriding the built-in methods, create a function with the same name and then perform actions.
Example
Here, override the “alert()” method which is a prebuilt method of JavaScript:
console.log("This is the overridden function");
};
Call the “alert()” method:
Output
While calling the “alert()” method, the overridden alert() will be called as shown in above output:
How to Override the User-defined Functions?
For overriding the user-defined function, let’s go over an example.
Example
Define a function “sum” with three parameters “a”, ”b” and “c” and it returns the sum of three numbers:
return a + b + c;
}
Override the function “sum” by defining a new function with the same name with two parameters ”a” and “b”:
return a + b;
}
Call the function “sum” by passing three numbers “5”, “10” and “3” as arguments:
Upon executing this code, the output is as:
The output displays “15” because the overridden function with two parameters “sum(a, b)” is called when calling the function “sum”.
How to Override a Function Using Inheritance?
In inheritance, the method of the parent class is overridden in the child class with the same name, same return type, and parameters. Let’s see an example of how a child class can override a method from a parent class.
Example
Create a class “Calculation” with method “calc”:
calc() {
console.log("Let's start calculations:");
}
}
Create a child class “square” that will extend with the parent class “Calculation”. Define a function in the child class with the same name, “calc”, with a parameter as in the parent class. This function will calculate the square of a number:
calc(x) {
console.log(x*x);
}
}
Create an object “sq” of the child class “square”:
Call the “calc” method by passing “6” as an argument:
The corresponding output will be:
It is observable in the output that the method calc() of the parent class was overridden by the calc() method of the child class
Conclusion
In JavaScript, the “Predefined” methods, “User-defined” functions, and “Parent class functions/methods” are overridden by creating the functions with the same name. However, the number of parameters can vary. The parent class’s function or method is overridden by the child’s method. This post describes the process for overriding functions in JavaScript.