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

122
Visualizações
Private fields in Javascript don't show up in JSON.stringify

So if I write a class as follows

class Rectangle {
   #width;
   #height;
   constructor() {
      this.#width = 3;
      this.#height = 5; 
   }

}

let rect = new Rectangle();

console.log(JSON.stringify(rect)); // returns {}

It will return an empty object, totally ignoring all of my private members. Adding a toJSON method works but that becomes very cumbersome. Is there any built-in way that I can easily get my private fields to show up in JSON.stringify? Or do I just have to write in every single member into a toJSON method?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Private properties are only accessible inside the class declaration itself. You'll need to write your own serialization method:

class Rectangle {
  #width;
  #height;
  constructor() {
    this.#width = 3;
    this.#height = 5;
  }

  stringify() {
    return JSON.stringify({['#width']: this.#width,['#height']: this.#height})
  }

}

let rect = new Rectangle();

console.log(rect.stringify())

about 4 years ago · Juan Pablo Isaza Relatório

0

One option to avoid having to write out all the members would be to have a single private data property on the instance, and then serialize / deserialize that property:

class Rectangle {
   #data;
   constructor(data) {
      this.#data = data;
   }
   getWidth = () => this.#data.width;
   toJson = () => JSON.stringify(this.#data);
}
const r = new Rectangle({ width: 1, height: 1 });
console.log(r.getWidth());
const stringified = r.toJson();
console.log(stringified);

const restructured = new Rectangle(JSON.parse(stringified));
console.log(restructured.getWidth());

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