Override a JavaScript function
In JavaScript, function overriding means redefining an existing function with a new implementation. It allows developers to change or extend the behaviour of a user-defined or built-in function during runtime.
- You can override both user-defined and built-in JavaScript functions.
- The new function replaces the old one with the same name.
- Useful for customizing existing logic or debugging without modifying original code.
- Overriding built-in functions (like
alert()orparseFloat()) should be done with caution. - The overridden function remains in effect for the entire scope where it’s defined.
[Approach 1]: Overriding a User-Defined Function
- You can redefine an existing function by assigning a new function with the same name.
- The new function replaces the old one during runtime.
- Useful when you want to update the behaviour of your own functions.
<body style="text-align:center;">
<h1 style="color:green;" id="h1">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 15px;
font-weight: bold;">
</p>
<button onclick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px;
font-weight: bold;">
</p>
<script>
var up = document.getElementById('GFG_UP');
up.innerHTML = "Click on the button to override"
+ " the function.";
var down = document.getElementById('GFG_DOWN');
function Fun() {
return "This is from old function";
}
down.innerHTML = Fun();
function GFG_Fun() {
var newFun = Fun;
Fun = function() {
return "This is from overridden function";
}
down.innerHTML = Fun();
}
</script>
</body>
[Approach 2]: Overriding a Built-in Function
- JavaScript allows modifying built-in functions (like
parseFloat,alert, etc.). - You can assign a new implementation to these functions, but it’s not recommended for production code.
- Commonly done for debugging, testing, or customization.
<body style="text-align:center;">
<h1 style="color:green;" id="h1">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 15px;
font-weight: bold;">
</p>
<button onclick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px;
font-weight: bold;">
</p>
<script>
var up = document.getElementById('GFG_UP');
up.innerHTML = "Click on the button to override"
+ " the function.";
var down = document.getElementById('GFG_DOWN');
down.innerHTML = "Floor value of '2.345' is ";
function GFG_Fun() {
// Override
parseFloat = function(x) {
return "Floor value of '2.345' is "
+ Math.floor(x);
}
// Overriding the parseFloat function and
// use it as Math.floor
down.innerHTML = parseFloat(2.345);
}
</script>
</body>