Object as a parameter in a JavaScript function

1

I looked in several places about using object as a parameter in a function, but I only found on this site , but I did not feel comfortable with this structure. what is the best way to parse an object as a JavaScript function parameter and set a default value?

Ex:

function teste(options) {
   options = (typeof options !== "object") ? {} : options;
   options.nome = options.nome || 'João';
   options.idade = options.idade || 20 ;
   console.log(options);
};
    
asked by anonymous 01.05.2015 / 05:26

1 answer

4

The answer you found seems appropriate. Since javascript does not use types for function parameters, you will need to validate if the passed parameter 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 concept of classes, so that you can validate if the passed object is an instance of the desired class. Here is 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 about the arguments passed to the construction of the Person object, such as:

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 gives you more control over created objects. But keep in mind that this does not prohibit the attributes of the person object from being changed after it is built, such as:

var jose = new Pessoa("José",35);
jose.nome = 0;

To avoid this kind of behavior, we need even more code complexity. I recommend you read this excellent Mozzila article on object orientation in Javascript: link

    
01.05.2015 / 05:43