Overloading functions in JavaScript


If you are a SharePoint developer, or do some general .NET development, you probably work with overloading methods. Using the same name you can define multiple variants of the same method by specifying a different set of parameters. As SharePoint 2010 contains a large piece of very powerful API in the JavaScript: both for communicating with the SharePoint platform (also known as the SharePoint Client Object Model) and manipulating the UI, the odds are high that you will sooner or later start using JavaScript more and will extend the functionality provided by SharePoint to meet your needs. While overloading might seem very straight forward, there is one thing that you need to remember while working with JavaScript.

…and that thing is: JavaScript does not support overloading!

Let’s have a look at the following example:

function addNumbers(n1, n2, n3) {
    return n1 + n2 + n3;
}

function addNumbers(n1, n2) {
    return n1 + n2;
}

var sum = addNumbers(1, 2, 3);

If overloading worked correctly the value of sum would be 6. However, as JavaScript doesn’t support overloading, the value of sum is something else.

JavaScript supports overriding not overloading, meaning, that if you define two functions with the same name, the last one defined will override the previously defined version and every time a call will be made to the function, the last defined one will get executed. Looking at the above example, the value of sum will be equal 3 instead of 6.

Why does the above matter? Imagine that you want to extend the SharePoint API with some function like for example one that allows you to display a message in the status bar and set the color of that message. If you would include such function in the SP.UI.Status namespace, just to make using it more intuitive, you would have a risk of someone else, perhaps even the SharePoint team, to overwrite your function with another implementation which might break your code. So the question is, while extending the SharePoint JavaScript API: should you extend the default namespaces or include the methods in one that you own yourself?

Technorati Tags: JavaScript

Others found also helpful: