Home > Software engineering >  Why doesn't the setter method body get called when using Javascript class syntax?
Why doesn't the setter method body get called when using Javascript class syntax?

Time:03-08

 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.

CodePudding user response:

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);

  • Related