Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

348
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!