-2

How can I create an object like that

var sum = {

  a : 5,
  b : 7,  
  sumar : function()
  {
    return (this.a+this.b);
  },
  sumar : function(a, b)
  {
    return (a+b);
  }

}

and then use any of the methods declared like this?

sumar0 = sum.sumar(); //use the method without parameters
sumar1 = sum.sumar(6,7); //use the method with parameters.

Just like "overriding" the methods? is this possible?

Thanks in advance and sorry for my bad english

r1oseko
  • 3
  • 1
  • 3
    What did you discover when you ran the code? – Andy Jul 14 '15 at 01:57
  • 5
    What you describe is called [***overloading***](http://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices). – PM 77-1 Jul 14 '15 at 01:57
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/arguments – Phil Jul 14 '15 at 01:59

1 Answers1

0

In Javascript, you do NOT declare two methods of the same name with differnt args like you do in some other languages. Instead, you declare only a single method with the name and then you examine the arguments when the function is called to decide which behavior you should follow.

When you do declare two properties with the exact same name, then one of them is ignored by the interpreter since there can only be one value for any given property in Javascript.

There is a long description of overloading in Javascript with a number of examples here:

How to overload functions in javascript?


In your specific case, you could test how many arguments were passed to the method and branch accordingly:

var sum = {

  a : 5,
  b : 7,  
  sumar : function(a, b)
  {
    if (arguments.length < 2) {
      // no arguments passed, use instance variables
      return (this.a+this.b);
    } else {
      // arguments were passed, use them
      return (a+b);
    }
  }

}

document.write(sum.sumar() + "<br>");
document.write(sum.sumar(6, 7) + "<br>");

Though, I must say, this is a particularly odd method that sometimes operates on the instance properties and sometimes doesn't.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979