Method Overriding In JavaScript

Introduction

 
It is true that JavaScript supports overriding, not overloading. When you define multiple functions that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed. The following example overrides the user-defined function.
 
JavaScript Demo - Overriding user-defined function
  1. <script type="text/javascript">  
  2.     function multiplyNum(x, y, z) {  
  3.         return x * y * z;  
  4.     }  
  5.   
  6.     function multiplyNum(x, y) {  
  7.         return x * y;  
  8.     }  
  9.     var result = multiplyNum(1, 2, 3);  
  10.     document.write(result);  
Output
 
2
Looking at the above example, the value of multiplication will be equal to 2 instead of 6.
 
In this case, the only function available is multiplyNum(x, y). So if we think we are making a call to multiplyNum(x, y, z), it's actually calling multiplyNum(x, y). The remaining parameter(s) will be ignored.
 
We can also override Javascript's built-in functions. The following example overrides the built-in JavaScript alert() function.
 
JavaScript Demo - Overriding built-in function
  1. <script type="text/javascript">  
  2.     var alert = function(message) {  
  3.         document.write(message);  
  4.     }  
  5.     // The following calls will invoke the overridden alert() function  
  6.     alert("Learn ");  
  7.     alert("JavaScript");  
  8. </script>  
Output
 
Learn JavaScript
 
By default, alert() function displays the message in the alert box. But here we have overridden it. Now it is displaying the message in the document.
 
I hope you enjoyed this article.
 
Thanks and regards.