Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to detour Built-In JavaScript Function

Tags:

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.

like image 599
Dev.K. Avatar asked Jun 13 '16 05:06

Dev.K.


1 Answers

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' );
like image 128
Michael Geary Avatar answered Sep 28 '22 03:09

Michael Geary