giugno 2005 Blog Posts

JavaScript: named parameters e overload di funzioni

JavaScript 1.5 non supporta i "named parameters" e nemmeno l'overload di una funzione. Giocando un po' è però possibile ottenere un surrogato degli stessi. Es. function AlertGenius(args){   var firstName, lastName;   switch (arguments.length)   {      case 1:         firstName = args.firstName;         lastName = args.lastName;         break;      case 2:         firstName = arguments[0];         lastName = arguments[1];         break;      default:         return;   }      alert("The genius is " + firstName + " " + lastName);}E' ora possibile invocare la funzione AlertGenius in due diversi modi:    AlertGenius( "Albert", "Einstein" ); oppure    AlertGenius( {lastName: "Einstein", firstName: "Albert"} ); Le due invocazioni producono lo stesso risultato.In realtà la seconda chiamata è zucchero sintattico per il seguente codice: function...

posted @ martedì 14 giugno 2005 19:04 | Feedback (3)