I would like to override a Javascript built-in function with a new version that calls the original (similarly to overriding a method on a class with a version that calls super in many languages). How can I do this?
For example…
window.alert = function(str) {
//do something additional
if(console) console.log(str);
//super.alert(str) // How do I do this bit?
}
Store a reference to the original function in a variable:
The universal way is
<original_func_reference>.apply(this, arguments)– To preserve context and pass all arguments. Usually, the return value of the original method should also be returned.However, it’s known that
alertis a void function, takes only one argument, and does not use thethisobject. So,_alert(str)is sufficient in this case.Note: IE <= 8 throws an error if you try to overwrite
alert, so make sure that you’re usingwindow.alert = ...instead ofalert = ....