Private Object & Class Properties

Keff - Mar 25 '20 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .