Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

350
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda