01.06.07
5 things you didn’t know about Javascript alert()
- alert() is a native method
- alert() is part of window
- alert() is part of this
- alert() can be rewritten
- alert() can be saved and reused
alert() is a dull function, useful for debugging and annoying users with messages that their password must contain at least one non-alphanumeric character. Let’s spice things up a bit while we find the true essence of this old companion.
1. Alert is a native method. It is not made up simply of other Javascript. This can be confirmed by typing javascript:alert(alert.toString()) into the location bar. We want to rewrite this, but luckily, the native code part will not stop us.
2. Alert is a function of window.
window.alert(”hello!”);
is the same as the non-window.alert() version.
3. alert() is part of ‘this’.
this.alert(”alert from this”);
This agrees with window being at the top level.
4. alert() can be rewritten.
function alert(message) {
document.writeln(message+”<br>”);
}
5. alert() can be saved and reused.
Sometimes while writing extensions, I want to dump some data through alert, but I want to limit the number of times alert can be called. Here is how to do this.
var temp_alert = alert;
alert = function(msg) {
if(alert.count++ < alert.max_alerts) {
temp_alert("Note from alert "+alert.count+": "+msg);
} else {
document.writeln("Max alerts reached!");
}
}
alert.count=0;
alert.max_alerts = 2;
alert("dude");
alert("dude");
alert("dude");
alert("dude");
Result:
Max alerts reached!
Max alerts reached!
Hallvord R. M. Steen said,
February 12, 2007 at 1:50 pm
#3 is a bit misleading since it’s only true if “this” refers to a window object.
For example
document.body.onclick=function(){
this.alert(); // fails, this is body
}