Object as parameter in a Javascript function

Asked

Viewed 4,690 times

1

I have looked in several places about the use of object as a parameter in a function, but only found on that website, but I didn’t feel comfortable with that structure. how best to put an object as a parameter of a Javascript function 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);
};

1 answer

4


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

  • Is there any other way to assign a default value other than "options.name = options.name || 'John';" ?

  • You could give an example using class and objects as a parameter?

  • I updated the answer, take a look.

  • Exactly that, I just imagined that there was a way to do it without using conditionals and so on, but for that I have to continue studying

Browser other questions tagged

You are not signed in. Login or sign up in order to post.