can I override in Javascript? -


how can create object

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

and use of methods declared this?

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

just "overriding" methods? possible?

thanks in advance , sorry bad english

in javascript, not declare 2 methods of same name differnt args in other languages. instead, declare single method name , examine arguments when function called decide behavior should follow.

when declare 2 properties exact same name, 1 of them ignored interpreter since there can 1 value given property in javascript.

there long description of overloading in javascript number of examples here:

how overload functions in javascript?


in specific case, test how many arguments passed method , branch accordingly:

var sum = {      : 5,    b : 7,      sumar : function(a, b)    {      if (arguments.length < 2) {        // no arguments passed, use instance variables        return (this.a+this.b);      } else {        // arguments passed, use them        return (a+b);      }    }    }    document.write(sum.sumar() + "<br>");  document.write(sum.sumar(6, 7) + "<br>");

though, must say, particularly odd method operates on instance properties , doesn't.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -