Is it possible to create object inside object in a constructor class?

Asked

Viewed 65 times

1

I am trying to create a Client class that has the following parameters:

{
"data": {
            "name": "Yuri Moura",
            "cpf": "123.456.789-00",
            "status": "Ativo",
            "contact": {
                "email": "[email protected]",
                "tel": "(00) 0000-0000"
            },
        }
}

I’m trying this way, but I don’t know how to create an object inside the object in a constructor:

class Cliente{
    constructor(name, cpf, contact, status) {
        this.name = name
        this.cpf = cpf
        this.status = status
        this.contact = contact{
            this.email = email
            this.tel = tel
        }
    }
}

    function cadastrarCliente() {
        let name = document.getElementById('name')
        let cpf = document.getElementById('cpf')
        let email = document.getElementById('email')
        let tel = document.getElementById('tel')
        let status = document.getElementById('status')

        let cliente = new Cliente(
            name.value, 
            cpf.value, 
            email.value, 
            tel.value, 
            status.value)

        console.log(cliente)
    }

1 answer

2


You can declare an anonymous object (no class) within your constructor.

class Cliente{
    constructor(name, cpf, status, email, tel) {
        this.name = name
        this.cpf = cpf
        this.status = status
        this.contact = {
            email,
            tel
        }
    }
}

Now if you want to work with classes like you’re already doing, you’ll need a contact builder.

class Contact{
    constructor(email, tel) {
        this.email = email
        this.tel = tel
    }
}

class Cliente{
    constructor(name, cpf, status, email, tel) {
        this.name = name
        this.cpf = cpf
        this.status = status
        this.contact = new Contact(email, tel)
    }
}
  • Using as anonymous object I was able to recover the parameters, thank you!

Browser other questions tagged

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