Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

260
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda