Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

359
Visualizações
ES6: Constructor function getters and setters

Why can't I set getters and setters in this way inside of the Constructor function?

function zConstructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    
    set fullname(text) {
        const parts = text.split(' ');
        this.firstName = parts[0];
        this.lastName = parts[1];
    }

    get fullname() {
        return this.firstName + ' ' + this.lastName;
    }
}

This getters and setters way works only in classes and Factory functions. What is the reason?

Thanks!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

A proper way of doing this is:

function zConstructor(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}
zConstructor.prototype = {
  set fullname(text) {
    const parts = text.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  },

  get fullname() {
    return this.firstName + " " + this.lastName;
  },
};

Your code does not work because setters and getters are meaningful for Objects only.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do it, but a constructor function is just a function, and the syntax of ordinary code blocks does not include the creation of setter and getter functions; there's no way to even make sense of what your code is supposed to mean, as far as the parser is concerned.

What you can do is use Object.defineProperties() to add the properties. Or, probably better, is to create them on the prototype either directly (again, with Object.defineProperties()), or by using a class declaration:

function zConstructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    
    Object.defineProperties(this, {
        fullname: {
            set: function(text) {
                const parts = text.split(' ');
                this.firstName = parts[0];
                this.lastName = parts[1];
            },
            get: function() {
                return this.firstName + ' ' + this.lastName;
            }
        }
    });
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda