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);

Comments 4

  1. Giorgio Maone wrote:

    Yes, it can be beaten quite easily:

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

    Posted 08 Apr 2009 at 12:23 pm
  2. Gareth Heyes wrote:

    @Giorgio

    Nice! Just another windmill war again then :(

    Posted 08 Apr 2009 at 12:29 pm
  3. Ehsun Amanolahi wrote:

    This code is great, is free to use?

    Posted 12 Apr 2009 at 3:42 am
  4. Gareth Heyes wrote:

    @Ehsun

    Yeah completely free

    Posted 12 Apr 2009 at 9:51 am

Post a Comment

Your email is never published nor shared. Required fields are marked *

Comment spam protected by SpamBam