Is it possible to combine the built-in JavaScript function

I am trying to see the argument passed to the JavaScript built-in alert () function using the following code. When I pass the argument, now I want to call a real (built-in) function so that the code does not interrupt.

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.

+5
source share
4 answers

I agree with Amin Jafari that it is not worth replacing the built-in functions at all, but there may be times when it is useful for testing or for other reasons.

However, the reason your code does not work is because your alert() replace function is in this form:

 function alert( text ) { ... } 

Function declarations are processed before any other code in the same area is executed. This is sometimes called the "lift function", although this is a bit wrong. (The function does not actually move, as the term "rise" implies).

In any case, this replaces the built-in alert() function before you save it in your built_in_alert variable.

Do it like this:

 alert = function( text ) { ... } 

Since you use the usual 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' ); 
+6
source

it would be better if you did not use the reserved name for your function, but if you really want to do this (which I say again, this is a bad idea), you should call the actual alert() using window : DEMO

 function alert(text)// Our custom alert function. { console.log('Alert function called with param :'+ text); window.alert("Calling with "+text); // try to call the actual built in alert() function. return 0; } alert("hi"); 
0
source

You can try the following:

 function custom_alert(text)// Our custom alert function. { console.log('Alert function called with param :'+ text); window.built_in_alert("Calling with "+text); return 0; } if (!window.built_in_alert) { window.built_in_alert = alert; window.alert = custom_alert; } 
0
source

Hi you look so

 <!DOCTYPE html> <html> <body> <button onclick="myFunction()">Click me</button> <p id="demo"></p> <script> function myFunction() { var text = "hello"; dynamicalert("Custom function "+text ) } function dynamicalert(_text) { alert(_text) } </script> </body> </html> 

if you want to use the name attribute then

Alerts (document.getElementsByName ("username") [0] .value);

-2
source

All Articles