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

261
Views
Why doesn't the setter method body get called when using Javascript class syntax?
 class Person{
    
      constructor(name,age){
        this.name = name;
        this.age = age;
      }
      get getName(){
        return this.name;
      }
      set setName(name){
        if (typeof name === 'number'){
          this.name = name;
        }else{
          this.name = 'joesy';
        }
      }
    
    }
    const p1 = new Person('jack',9);
    console.log(`${p1.name}`);
    p1.name = 11;
    console.log(`${p1.name}`);

I want to be able to check that the parameter passed into the set method is a number and not a string, but it seems that no matter how I write the if statement inside setName(), calling p1.name = value will always set value to x.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Javascript objects can have two different types of properties:

  1. data properties and
  2. accessor properties (getter/setter).

Data properties simply store values assigned to them (if they are writable) and return these stored values when read.

Accessor properties do not store values at all. Instead they work as functions that are executed whenever read access (getter) or write access/assignment to the property (setter) happens.

Here's a basic example:

class Person {
  constructor(firstName, lastName) {
    // data properties
    this.firstName = firstName;
    this.lastName = lastName;    
  }
  
  // accessor property
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
  
  set fullName(name) {
    let [firstName, lastName] = name.split(' ');
    this.firstName = firstName;
    this.lastName = lastName;  
  }
}


const p1 = new Person('John', 'Doe');
const p2 = new Person();
p2.fullName = 'Christine Smith';

console.log(p1.firstName, p1.lastName, p1.fullName);
console.log(p2.firstName, p2.lastName, p2.fullName);

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!