Sponsored Ad

Sunday, February 7, 2010

JavaScript Overriding Functions

This is a way to use a closure to override the document.getElementById () function, so that we can add two additional parameters. In general, we should store the original function so that we could use our own function:

  1. // store the original document.createElement
  2.     var _createElement = document.createElement;
  3.      
  4.     //override document.createElement
  5.     document.createElement = function(tag)
  6.     {
  7.         var _elem = _createElement(tag);
  8.         eval("_elem." + name + " = fn");
  9.         return _elem;
  10.     }

Although technically there is nothing wrong with this approach, the creation of a global variable is difficult and perhaps even error prone. A better way is to pass the original document.createElement () for ours to be kept in memory. That allows us to delegate the creation of node to it. Instead of creating a function that could only be called once, you can use one in line to run immediately, and store the results in our document.createElement () replaced the function

  1. document.createElement = (function (fn)
  2.     {
  3.         return function (type, id, className)
  4.         {
  5.             var elem = fn.call(document, type);
  6.             if (id) elem.id = id;
  7.             if (className) elem.className = className;
  8.      
  9.             return elem;
  10.         };
  11.     })(document.createElement);

0 comments:

Post a Comment

Sponsored Ad

More Related Articles

Website Update

Followers