The answer you found seems appropriate. Since javascript does not use types for function parameters, you will need to validate whether the parameter you passed is actually an object:
options = (typeof options !== "object") ? {} : options;
If another type of variable is passed, it creates an empty object.
Another problem is if the passed object does not have the desired attributes. This explains the following lines:
options.nome = options.nome || 'João';
options.idade = options.idade || 20 ;
A more appropriate way to solve this is to use the class concept, so that you can validate whether the past object is an instance of the desired class. Follow an example:
//método construtor da classe
var Pessoa = function(nome, idade){
//this se refere ao objeto que está sendo instanciado
this.nome = nome || 'João';
this.idade = idade || 20 ;
}
function teste(pessoa){
pessoa = pessoa instanceof Pessoa ? pessoa : new Pessoa;
console.log(pessoa);
}
You can make more validations regarding the arguments you passed for constructing the Person object, for example:
var Pessoa = function(nome, idade){
if(typeof nome != 'string' || nome.length < 3){
this.nome = 'João';
}else{
this.nome = nome;
}
if(isNaN(idade) || idade < 0){
this.idade = 20 ;
}else{
this.idade = idade;
}
}
This allows you greater control over the created objects. But keep in mind that this does not prohibit the attributes of the person object from being changed after its construction, for example:
var jose = new Pessoa("José",35);
jose.nome = 0;
To avoid this kind of behavior, we need even more complexity in the code. I recommend you read this excellent article by Mozzila regarding object orientation in Javascript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
possible duplicate of How to put default (default) arguments in a Javascript function?
– Felipe Fonseca
Really it is very similar, only with the differential of being using objects, that from those examples it is possible to adapt them.
– adrianosymphony