I'm trying to see argument passed to a built in JavaScript function alert() using following code. Once I get the argument passed to it, now I want to call the real(built-in) function, so that the code doesn't break.
built_in_alert = alert;
function alert(text)// Our custom alert function.
{
console.log('Alert function called with param :'+ text);
built_in_alert("Calling with "+text) // try to call the actual built in alert() function.
return 0;
}
alert("hi");
This code somehow goes to infinite recursion.
I agree with Amin Jafari that it's generally not a good idea to replace built-in functions, but there can be cases where it's useful for testing or other reasons.
That said, the reason your code doesn't work is that your replacement alert()
function is in this form:
function alert( text ) { ... }
Function declarations are processed before any other code in the same scope is executed. This is sometimes called "function hoisting", although that is a bit of a misnomer. (The function isn't actually moved as the term "hoisting" implies.)
In any case, this replaces the built-in alert()
function before you save it into your built_in_alert
variable.
Do it like this instead:
alert = function( text ) { ... }
Because you're now using an ordinary assignment to replace the built-in alert()
, the replacement happens when and where you expect it.
Try it here:
built_in_alert = alert;
alert = function( text ) {
console.log( 'Alert function called with param :'+ text );
built_in_alert( 'Calling with ' + text );
}
alert( 'hi' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With