Tuesday 7 October 2014

Hoax about javascript method overloading and overriding

I have seen developers associating method overloading and overriding with javascript, and they are pretty confused with the concept.


The question goes - "If we have two methods with the same name, and we try to call the method, which one will be called"

The most common answer I got was "Randomly any of the method is called"!!!

Actually, javascript doesn't have a Random behaviour:


Example 1:

function process()
{
console.log('process 1');
}
function process()
{
console.log('process 2');
}
function calllingProcess()
{
      for(var i=0;i<100;i++)
{
process();
}
}

So, if I call the method "process"
Result : "process 2" will be printed. And yes ALWAYS!!!

Reason: The methods are present in the same namespace, so when the executor finds a method which already exists, it overrides the first method.

Example 2:

function process(param)
{
console.log('process 1');
}
function process()
{
console.log('process 2');
}
function calllingProcess()
{
      for(var i=0;i<100;i++)
{
process('Hello');
}
}

So, any guess??
Result: "process 2" will be printed. And yes this time also, ALWAYS!!!


These were the basic, which I thought would be helpful.
Please do write to me @ sashiks1009@yahoo.com in case of any issue.



2 comments:

  1. Thanks for throwing light on this confusing topic. I feel enlightened :)

    ReplyDelete