I am trying declare a private class variable for a super class and I seem to have trouble doing so. I there something I am missing? This is my code so far.
class Animal {
constructor(_name) {
this._name = _name;
}
name() {
console.log(`${this._name} is my name.`);
}
}
new Animal('Bob').name();
Private fields start with # but their scope will keep them hidden from subclasses.
class Animal {
#name
constructor(name) {
this.#name = name;
}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields
Private class features are available in the following browsers:
| Chrome | Edge | FireFox | Opera | Safari |
|---|---|---|---|---|
| 74+ | 79+ | 90+ | 62+ | 14.1+ |
Here is an example of your class with a private instance field called name:
class Animal {
#name;
constructor(name) {
this.#name = name;
}
get name() {
return this.#name;
}
toString() {
return `${this.#name} is my name.`;
}
}
const bob = new Animal('Bob');
console.log(bob.name);
console.log(bob.toString());
// console.log(bob.#name); <-- SyntaxError