Polymorphic Functions in Javascript

Last Updated on: October 10, 2022

It is possible to define multiple functions with the same name in JavaScript, and the last one 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 accidentally create two functions with 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 we pass to it and then works 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.


Get notified of new posts:


Similar Posts

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *