JavaScript By Example
Functions in JavaScript are not static where they do the same thing every time you call them. Apart from being able to redefie a function at any subsequent point in the processing so that it will do something different for all the subsequent calls, we can also redefine a function from within the function itself.
With this example we are going to create one of two different addEvent functions depending on which of the two ways that the current browser supports for adding events - either addEventListener or attachEvent.
Instead of defining one or other of those functions when the page first loads though, we are instead going to wait until the page actually calls addEvent before deciding which of the two functions to define. That way if the page never calls attach Event the code to test which version the browser supports doesn't need to run. We do this by creating a third addEvent function that encloses the other two which when called for the first time will redefine the addEvent function to be whichever of the two that the browser supports and will then call that function.
With this example we are going to create one of two different addEvent functions depending on which of the two ways that the current browser supports for adding events - either addEventListener or attachEvent.
Instead of defining one or other of those functions when the page first loads though, we are instead going to wait until the page actually calls addEvent before deciding which of the two functions to define. That way if the page never calls attach Event the code to test which version the browser supports doesn't need to run. We do this by creating a third addEvent function that encloses the other two which when called for the first time will redefine the addEvent function to be whichever of the two that the browser supports and will then call that function.
addEvent = function(ob, type, fn ) {
if (window.addEventListener)
addEvent = function(ob, type, fn ) {
ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
var eProp = type + fn;
ob['e'+eProp] = fn;
ob[eProp] = function(){ob['e'+eProp]( window.event );};
ob.attachEvent( 'on'+type, o[eProp]);
};
addEvent(ob, type, fn )
};
addEvent(document.getElementById('myid'),
'click',
myfunction);