Overwriting native functions in javascript

I research a lot of Javascript as part of my job and I’ve been toying with the idea of a perfect native function overwrite. The idea is that you can still call the native function and have control over it but once it’s been defined it cannot be modified only destroyed.

My idea was to redefine the alert function and to remove it once it reaches a certain limit, in order to avoid infinite prompts. I think I’ve been successful but I’m sure someone will point out if I haven’t. It works by storing the native function in a closure and holds the reference within it’s parent. The child function is then returned with two private variables the native function call and a counter. Because they are private variables they shouldn’t be available in the global scope and so only the parent of the the child function should have access to them.

This code is based on the assumption that it is run first before any other Javascript, so you can modify it after it’s been executed but you should no longer have access to it’s native code.

window.alert = function(native) {
 var counter = 0;
 return function(str) {    
    native(str);
    if(counter > 10) {
      window.alert = null;
    }
    counter++;
 }
}(window.alert);

4 Responses to “Overwriting native functions in javascript”

  1. Giorgio Maone writes:

    Yes, it can be beaten quite easily:

    http://sla.ckers.org/forum/read.php?2,15812,27520#msg-27520

  2. Gareth Heyes writes:

    @Giorgio

    Nice! Just another windmill war again then 🙁

  3. Ehsun Amanolahi writes:

    This code is great, is free to use?

  4. Gareth Heyes writes:

    @Ehsun

    Yeah completely free