Private field must be declared in an enclosing class in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Private field must be declared in an enclosing class #

The "Private field must be declared in an enclosing class" error occurs when we try to read a private value directly from our code outside of the class object. To solve the error, make sure to only read private values from inside of the class.

private field must be declared in enclosing class

Here's an example of how the error occurs.

index.js
class Person { #num = 100; } const p = new Person(); // ⛔️ Private field '#num' must be declared in an enclosing class console.log(p.#num);

We got an error because we tried to access a private value directly in our code, outside of the class.

Private fields (fields prefixed with #) are accessible on the class constructor from inside the class declaration.

To solve the "Private field must be declared in an enclosing class" error, make sure to only access private fields from inside the class.

index.js
class Person { // 👇️ Private field #num = 200; constructor(first, last) { this.first = first; this.last = last; } getNum() { // 👇️ Accessing private field return this.#num; } getName() { // 👇️ Calling private method return this.#fullName(); } // 👇️ Private Method #fullName() { return `${this.first} ${this.last}`; } } const p = new Person('James', 'Doe'); console.log(p.getName()); // 👉️ "James Doe" console.log(p.getNum()); // 👉️ 200

We declared a private field #num and a private method #fullName.

Make sure to declare any private fields before accessing them.

We are able to access the private field and method from inside the scope (inside of the class), but if we try to access them directly from our code, we would get the error.

To get around this you have to implement methods in the class that interact with the private fields and methods, and you have to expose these methods.

You can also initialize a private field without a value and set its value at a later point.

index.js
class Person { // 👇️ Private field #num; increment() { this.#num = typeof this.#num === 'number' ? this.#num + 100 : 100; return this.#num; } } const p = new Person(); console.log(p.increment()); // 👉️ 100 console.log(p.increment()); // 👉️ 200 console.log(p.increment()); // 👉️ 300

We declared a private field #num without initializing its value. Note that a private field can only be defined once in a single class.

Use the search field on my Home Page to filter through my more than 3,000 articles.