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

131
Visualizações
Can I use private fields in es5 if not how do you implement private fields in es5 constructor functions?

I have been learning how classes work "under the hood" by implementing them using es5. Since javascript classes are just "syntactical sugar". I remember reading that classes just get converted into regular es5 functions. For example

class Dog {
  constructor(name) {
    this.name = name
  }
  speak(text){
    console.log(text)
  }

}
const mydog = new Dog("bruno")
mydog.speak("I do be liking my bones thicc")

gets converted to something like this (but using the "this" keyword of course)

function Dog(name) {
  const dog = Object.create(Dog)
  dog.name = name
  Dog.prototype.speak = function (text) {
    console.log(text)
  }
  return dog
}
const mydog = Dog("bruno")
mydog.speak("I know I could have refactored to used the 'new' keyword instead")

Here is the problem, I can't seem to be able to implement private fields. Shouldn't this be possible if classes are just "syntactical sugar and javascript remains prototype based?

For example, trying to convert the following class

class ClassWithPrivateField {
  #privateField;

  constructor() {
    this.#privateField = 42;
    delete this.#privateField;   // Syntax error
    this.#undeclaredField = 444; // Syntax error
  }
}

const instance = new ClassWithPrivateField()
instance.#privateField === 42;

into an es5 constructor function as follows doesn't work. It gives the error,

"#privateField' must be declared in an enclosing class"

function ClassWithPrivateField (){
  #privateField;

    this.#privateField = 42;
    delete this.#privateField;   // Syntax error
    this.#undeclaredField = 444; // Syntax error
}

const instance = new ClassWithPrivateField()
instance.#privateField === 42;
about 4 years ago · Juan Pablo Isaza
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