DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Keff
Keff

Posted on

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

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

β­οΈπŸŽ€ JavaScript Visualized: Promises & Async/Await

async await