quarta-feira, 30 de janeiro de 2013

Argumentos opcionais em Javascript

Ás vezes precisamos alterar uma função que já existe, adicionando mais parâmetros.
Pra não quebrar a compatibilidade com outras partes do sistema que estejam usando a função, e pra não precisar revisar tudo pra encontrar as chamadas à tal função,  o jeito é criar os novos parâmetros como opcionais.

 function war(enemy,reason) {  
      if(!enemy) { //The mandatory argument is not present - die with error(no pun intended)  
           alert("Please choose an enemy before starting a war");  
           return false;  
      }  
      if(!reason) { //If the optional argument is not there, create a new variable with that name.  
           var reason = "They have Nukes!";  
      }  
      /* ...Do what you want with the arguments... */  
 }  
Fonte: http://www.openjs.com/articles/optional_function_arguments.php

Nenhum comentário: