Polymorphic Functions

by jeremyjones on March 21, 2011

  • Share
  • CevherShare
  • Share

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the one that runs. This is unlike other languages where you can distinguish between functions by using a different number of arguments when you call the function.

Most programmers will only think about this aspect of JavaScript when they accidently create two functions that have the same name. This can happen when you incorporate two different scripts on the same page. You could see this as a problem with the JavaScript language, but this method of handling duplicate function names can make JavaScript function processing even more polymorphic.

It is relatively simple to recode a function to give each a different name and then set up an extra function. This extra function examines the type, and number of parameters that we pass to it and then use that to work out which of the other functions to call.

This is not as efficient as a language that performs this selection automatically, but it allows us to make the functions even more polymorphic. It is possible to configure JavaScript so that the functions change themselves. A basic example of this is shown below:

function addEvent(obj,evt,fn) {

if (document.addEventListener) {
addEvent = function (obj,evt,fn) {
obj.addEventListener(evt,fn,false);
}
}

else >if (document.attachEvent) {
addEvent = function (obj,evt,fn) {
obj.attachEvent('on'+evt,fn);
}
}
addEvent(obj,evt,fn);
}

When you run this function, it creates another function with the same name. This new function is the one that will run for all subsequent calls, but the first time the original function will run.

Leave a Comment

Previous post:

Next post: