1

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;
  • The last line from the first example ... `instance.#privateField === 42;` ... will throw a syntax error too. The OP might have a look at ... [Get Private Method Value at Public Method in JavaScript](https://stackoverflow.com/questions/69241463/get-private-method-value-at-public-method-in-javascript) – Peter Seliger Oct 15 '21 at 20:07
  • I know. I removed the "syntax error" comment. not sure why – Personal Information Oct 15 '21 at 23:49

0 Answers0