- Overriding in JavaScript
- How does Overriding work in JavaScript?
- Types of Overriding in JavaScript
- 1. The First Behaviour
- 2. The Second Behaviour
- 3. The Third Behaviour
- Conclusion
- Recommended Articles
- Override a Function in JavaScript
- Override Custom Functions in JavaScript
- Override Built-In Functions in JavaScript
- Try to Overload a Function in JavaScript
- Use the super Keyword in Inheritance to Get Back Previous Function
- Related Article — JavaScript Function
Overriding in JavaScript
To understand the concept of overriding in JavaScript, let us first revise the concept of overriding as-a-whole.
Web development, programming languages, Software testing & others
Method Overriding is an OOPs concept closely knit with inheritance. When a child class method overrides the parent class method of the same name, parameters and return type, it is termed as method overriding. Also, be reminded that this is completely different from the concept of method overloading. Method overloading occurs when there are two functions with the same name but different parameters.
Now, let us try to understand this concept from JavaScript’s point of view. We know that JavaScript is “relatively” not object-oriented. It does have the concept of Objects which qualifies it to be object-oriented, but it does not have the concept of Classes. It is prototypical in nature. Yes yes, I hear you shouting loud that we can declare classes in JavaScript but let me remind you that this Class notation is merely a syntactical sugar to the underlying prototypical architecture.
So, JavaScript does support the concept of method overriding. And it does it in very strange ways. After all, it is the most misunderstood language in the programming world. JavaScript supports overriding, but not overloading.
Note – Throughout the examples in this article, we would be using the developer console of the browsers. Simply open the browser developer tools (Ctrl/Cmd + Shift + C) and go to the Console tab in the developer tools window.
It looks like this in Chrome:
This is the playground for most of the JavaScript related concepts. We would be using this playground throughout this article.
How does Overriding work in JavaScript?
In JavaScript, all the objects inherit from the Object prototype. All objects are instances of Object. Thus, whenever you create any new object, JavaScript automatically defines a _proto_ (prototype) property for the new object. When a child object is created, it again has a _proto_ property and so on. Now, when you try to access a method or a property of an object, JavaScript first checks if the object has that method/property. If it does not, JavaScript checks if the object’s _proto_ has that method/property. If not, JavaScript checks if its parent object’s _proto_ has that method/property. It continues searching up the chain until either the method/property is found or the _proto_ of Object is encountered and searched. E.g. Date.prototype.[[Prototype]]is Object.prototype.
Now see the chain upside down. This is how overriding works in JavaScript. A method would continue to override the parent object’s method even if it is a method of Object. For example, we can even override the core functionality such as creating a Date object.
Let us see this with an example:
new Date(); //the JavaScript Date() method //overriding the JavaScript Date() method function Date()< this.date = "This method overrides the default constructor of Date class."; >; var date2 = new Date(); console.log(date2);
Types of Overriding in JavaScript
There are no types of overriding defined in JavaScript. However, based on the behavior of the programming language, we can say that method overriding in JavaScript works in the following ways.
1. The First Behaviour
The first way is the one we saw above when we defined a method to override the default Date constructor of JavaScript. This is in a way similar to the third way illustrated below because all objects in JavaScript are an instance of the Object prototype. What differentiates the third behavior is the use of the super keyword. We will see more when we illustrate the third behavior.
Let’s see another similar example. This time, we would override the alert functionality. The default behavior of the alert function in JavaScript is to display a small dialogue box on top of the page with the message that we pass as a parameter.
Now, when we override it with our own code, the default alert function is no longer called.
function alert(msg) < console.log(msg); >; alert("This is an alert.");
2. The Second Behaviour
The second way is when we try to overload functions in JavaScript. Remember, JavaScript does not support function overloading. So, instead of overloading your function, JavaScript would override all previous definitions of your function with the latest one.
Let us see this in action.
//Calculate area of rectangle function calculateArea(x, y) < return x*y; >//Calculate area of square function calculateArea(a) < return a*a; >console.log("Area of rectangle 2x3 is : " + calculateArea(2, 3)); console.log("Area of square 5x5 is : " + calculateArea(5));
Notice the result. JavaScript always calls the second definition of the function and returns the square of the first parameter. The subsequent parameters are ignored.
3. The Third Behaviour
The third behavior comes into picture when we involve classes and inheritance in JavaScript. When a child class inherits the methods of parent class and defines its own methods with the same name, the parent class methods are overridden. This is not what we would want in real-life applications. We would want our parent class methods to be accessible even when overridden by child class methods. So, the super keyword comes to our rescue. Using the super keyword, we can access the parent class methods.
Let us see this in action.
//the parent class class Person < greet() < console.log("Hello. I am a person."); >; > //the child class class Employee extends Person < greet() < super.greet(); //calling parent class method via keyword 'super' console.log("Hello. I am an employee."); >> let per = new Person(); //parent class object let emp = new Employee(); //child class object per.greet(); emp.greet();
Now go back to the first behavior example and try using the super keyword there. You would notice it doesn’t work. This is because when we created our method in the first example, we did not extend the parent class. We created the method in the global scope thus overriding all other definitions of the method.
Conclusion
Let us revise our understanding of method overriding in JavaScript. We learned that JavaScript does support overriding, but not overloading. If we try to overload methods, JavaScript overrides all previous definitions by the latest one. This is true even for core functions!
Next, we saw how we can override methods in child classes and subsequently access parent class methods as and when required. This is a very useful concept as it allows us to extend the functionality of our parent classes and thus improves code reusability.
Recommended Articles
This is a guide to Overriding in JavaScript. Here we discuss How does overriding works in JavaScript and Types of overriding in JavaScript. You may also look at the following article to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVASCRIPT Course Bundle — 83 Courses in 1 | 18 Mock Tests
343+ Hours of HD Videos
83 Courses
18 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
Override a Function in JavaScript
- Override Custom Functions in JavaScript
- Override Built-In Functions in JavaScript
- Try to Overload a Function in JavaScript
- Use the super Keyword in Inheritance to Get Back Previous Function
In this tutorial article, we will introduce how to override a function in JavaScript. We will also go through how the JavaScript interpreter behaves when we overload a function or use it with inheritance.
JavaScript does not support overloading. But it allows overriding functions. In the case of declaring two functions with the same name and parameters, JavaScript considers the latest function while interpreting. This is how to override a function in JavaScript.
Override Custom Functions in JavaScript
We will create two custom functions with the same name, Emp_name , to display the employee’s name with different alert() messages.
Example code without override function:
function Emp_name(e) return "Hello, " + e + "! This is the default function's message."; > alert(Emp_name("Harry"));
Example code with override function:
function Emp_name(e) return "Hello, " + e + "! This is the default function's message."; > alert(Emp_name("Harry")); function Emp_name(e) return "Hello, " + e + "! This is overriden function's message."; > alert(Emp_name("Harry"));
Override Built-In Functions in JavaScript
JavaScript also allows overriding built-in functions in the same way. When we change the code block of a function with the same name as that of a predefined function, it overrides the default function and changes its code to the new one. We will use the Date() function and override it. By default, the Date() function displays date, day, and local time. We will override it to display an alert() message.
var d = new Date(); document.write(d); function Date() return "This is the overriden function."; > alert(Date());
Try to Overload a Function in JavaScript
JavaScript does not allow overloading a function. Instead, it will override the function. We will create two functions named sum to add different numbers of parameters.
function sum(i, j, k) return i+j+k; > function sum(i, j) return i+j; > alert("Sum of i+j+k is: " + sum(4, 5, 8)); alert("Sum of i+j is: " + sum(4, 5));
The output will show the addition for only the first two parameters for both functions. This is because function overloading is not allowed. Hence, the interpreter will consider the latest function and the parameters it defines. All the additional parameters will be ignored.
Use the super Keyword in Inheritance to Get Back Previous Function
The only way to get back the previous function once we override it is to use the super keyword. We will create two functions with the same name and parameters, one in the parent class and one in the child class. We will use the super keyword to access the parent class function even after overriding it.
class Parent msg() document.write("This is parent class msg.
"); > > class Child extends Parent msg() super.msg(); document.write("This is child class msg."); > > let p = new Parent(); let c = new Child(); p.msg(); c.msg();
Kailash Vaviya is a freelance writer who started writing in 2019 and has never stopped since then as he fell in love with it. He has a soft corner for technology and likes to read, learn, and write about it. His content is focused on providing information to help build a brand presence and gain engagement.