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;