DEV Community

Keff
Keff

Posted on

4 4

Private Object & Class Properties

Easy and clean way of creating private object methods and properties, making use of Symbols

// Object with private field
function privateProps() {
    const priv = Symbol('private prop');

    return {
        [priv]: {
            id: '1111-2222-3333-4444'
        },
        getSomething() {
            return fetch(`http://.../users/${this[priv].id}`);
        }
    }
}

const obj = privateProps();
obj.getSomething(); // Accesible
obj[priv]           // 'undefined' as we don't have access to priv, 
                    //  we can't re-create the symbol from outside as it is unique.
Enter fullscreen mode Exit fullscreen mode

Using in a class?

I don't like this pattern that much, but it can be useful in some cases.
There are other ways of accomplishing this, this is just one example.

const MyClass = (() => {
  const priv = Symbol('private');

  return class {
    constructor(name) {
      this[priv] = name;
    }

    getName(){
      return this[priv];
    }
  }
})();

let instance = new MyClass('test');
instance.private;   // undefined
instance.priv;      // undefined
instance.getName(); // 'test'
Enter fullscreen mode Exit fullscreen mode

Currently there is a proposal for adding private fields to classes, check it out here

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up