DEV Community

Cover image for Class Fields in JavaScript πŸ”₯
Suprabha
Suprabha

Posted on

Class Fields in JavaScript πŸ”₯

In JavaScript, there are two types of object fields (properties and methods):

1️⃣ Public πŸ‘­

Accessible from anywhere. They comprise the external interface. Until now we were only using public properties and methods.

2️⃣ Private πŸ”

Accessible only from inside the class. These are for the internal interface.

Class fields are public by default, but private class members can be created by using a hash # prefix.

Class Field Syntax

  • You can define new private members
  • You will get error if you break the access rule
  • It has public and private static fields, which allow you to declare class member that can be accessed without creating instance of the class

Using variable like _variableName, it means we can use that variable only in the class.

example

class GetDateTime {
    _start = 0

    getDate() {
        if(true) {
            this._start = new Date()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

But this does not prevent _start variable accessible publicly. Checkout here πŸ‘‡

let date = new GetDateTime()
console.log(date._start) 
// Thu Jun 24 2021 16:36:06 GMT+0530 (India Standard Time)
Enter fullscreen mode Exit fullscreen mode

To create real private instance you can use # to create private variables.

πŸ“ NOTE: You just need to replace _ with #

class GetDateTime {
    #start = 0

getDate() {
        if(true) {
            this.#start = new Date()
        }
    }
}

let date = new GetDateTime()
console.log(date.#start) 
// Uncaught SyntaxError: Private field '#start' must be declared in an enclosing class
Enter fullscreen mode Exit fullscreen mode

The encapsulation is enforced by language.

It has also support for private methods.

Example:

class GetDateTime {
    #start = 0

  getDate() {
    if(true) {
        return this.#getNow()
    }
  }

  #getNow() {
    this.#start = new Date()
  }
}

let date = new GetDateTime()
console.log(date.getDate()) 
// Thu Jun 24 2021 16:55:32 GMT+0530 (India Standard Time)
Enter fullscreen mode Exit fullscreen mode

The private methods can only be accessible inside of the class.

Private static fields

You can also create private static variable.

The limitation of static variables being called by only static methods still holds.

class GetDateTime {
    static #start = 0

    static getDate() {
        if(true) {
            this.#start = new Date()
            return this.#start
        }
    }
}
console.log(GetDateTime.getDate()) 
// Thu Jun 24 2021 17:53:02 GMT+0530 (India Standard Time)
Enter fullscreen mode Exit fullscreen mode

Reference 🧐

Private Class Fields

Buy Me A Coffee

🌟 Twitter πŸ‘©πŸ»β€πŸ’» suprabha.me 🌟 Instagram

Top comments (3)

Collapse
 
anupam17 profile image
anupam-17

Please suggest me some free sources to learn react js

Collapse
 
thexdev profile image
M. Akbar Nugroho

Great article supraba! Just want to give you a feedback. I think you should change your cover. It tells me that _ means it can aceessed publicy :).

Collapse
 
suprabhasupi profile image
Suprabha

True, _ means we can access publicly