Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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); 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading