My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Monday, February 12, 2007

Could I change a native function ?

Just a quick post about how to modify a document (and others generic objects) native methods.


// basic example
document.createElement = (function(createElement, Element){
return function(nodeName){
var element, key;
try{element = createElement(nodeName)}
catch(e){element = createElement.call(document, nodeName)};
for(key in Element)
element[key] = Element[key];
return element;
}
})(document.createElement, {});


What's that ?
... a really simple way to extend with your defined object each element created using document.createElement function.
This is an example with useful comments (I hope)

// redefine document.createElement native function
// using anonymous function
document.createElement = (
function(
// original document.createElementFunction
createElement,

// object used to extend created elements
Element
){

// new document.createElement function
return function(

// type of element (div, p, link, style ... )
nodeName
){

// element and key to loop over object
var element, key;

// IE like this
try{element = createElement(nodeName)}

// FireFox like that
catch(e){element = createElement.call(document, nodeName)};

// loop over Element
for(key in Element)

// and assign each method to new element
element[key] = Element[key];

// return created element
return element;
}
})(
// send to anonymous, the original function
document.createElement,

// send object used to extend created elements too
{
// read firstChild node
read:function(){
return this.firstChild.nodeValue
},

// write text into node
write:function(text){
this.appendChild(document.createTextNode(text))
}
}
);

// basic example
onload = function(){
var div = document.createElement("div");
document.body.appendChild(div);
div.write("Hello World !!!");
alert(div.read()); // Hello World !!!
};

That's all, and this method is only a basic native method override example, have fun with JavaScript :-)

1 comment:

qui.nguyen said...

So cool script. Could you tell me how can you write that script, my mean is where is the knowledge you obtain to able to write that script? I try research in many places, but only find the solution with your script. Thank you very much.