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

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay