Home » Nodejs » How to declare private variables and private methods in es6 class [duplicate]

How to declare private variables and private methods in es6 class [duplicate]

Posted by: admin November 29, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

One way to achieve this is using another ES2015 feature known as modules.

You may already be familiar with AMD modules, or commonJS modules (used by Nodejs). Well ES6 / ES2015 brings a standard for JS – we’ll call them ES6 modules but they are part of the JS language now. Once you have modules, you have the ability to do information hiding for both private functions and object variables. Bear in mind, only what you “export” is visible to client calling code.

Lets work through your example code. Here is a first cut:

person.js

 const getNameWithInitial = function () {
      let initial = this._gender === 'male' ?
      'Mr. ' :
      'Mrs. ';
      return initial + this._name;
    }

  export class Person {

    constructor(name, gender) {
        this._name = name;
        this._gender = gender;
      }

      get name() {
          return getNameWithInitial.call(this);
        }
    }
  }

client.js

import {Person} from './person';
const manas = new Person('Manas', 'male');
console.log(manas.name);  // this calls what was your getName function

Now, the getNameWithInitial function is effectively private, as it is not exported, so client.js cannot see it.

However, we still have a problem for the Person class, since this is exported. At the moment you can just walk up to manas object and do:

manas._name = 'Joe'

With properties like _name, we can combine modules and symbols. This is a powerful yet lightweight information hiding technique available with ES6+/ES2015.

Symbol is a new built-in type. Every new Symbol value is unique. Hence can be used as a key on an object.

If the client calling code doesn’t know the symbol used to access that key, they can’t get hold of it since the symbol is not exported.

Let’s see our modified code to make use of symbols and modules to hide Class attributes.

person.js

const s_name = Symbol();
const s_gender = Symbol();

const getNameWithInitial = function () {
  let initial = this[s_gender] === 'male' ?
    'Mr. ' :
    'Mrs. ';
  return initial + this[s_name];
}

export class Person {

  constructor(name, gender) {
    this[s_name] = name;
    this[s_gender] = gender;
  }

  get name() {
    return getNameWithInitial.call(this);
  }
}

So, now a client cannot just do:

 manas._name = 'Joe' 

because _name is not being used as the key for the name value.

However, symbols are exposed via reflection features such as Object.getOwnPropertySymbols so be aware they are not “completely’ private using this technique.

import {Person} from './person';
const manas = new Person('Manas', 'male');
const vals = Object.getOwnPropertySymbols(manas);
manas[vals[0]] = 'Joanne';
manas[vals[1]] = 'female';

Takeaway message – Modules in general are a great way to hide something because if not exported then not available for use outside the module, and used with privately stored Symbols to act as the keys, then class attributes too can become hidden (but not strictly private). Using modules today is available with build tools eg. webpack / browserify and babel.

Questions:
Answers:

If you would like an analogue to the ES5 solution, it’s quite simple; the constructor simply becomes what holds the closure, and you add any methods/objects which should remember the private state in there.
Prototyped methods have no access to the closure of the initial constructor, without using some privileged getters:

class Person {

  constructor ({ name, age, deepDarkSecret }) {
    const bribe = () => console.log(`Give me money, or everybody will know about ${ redactRandom(deepDarkSecret) }`);

    Object.assign(this, { name, age }); // assigning publicly accessible values
    Object.assign(this, { bribe }); // assign "privileged" methods (functions with closure-reference to initial values)
  }

  recallSecret () {
    console.log("I'm just a prototyped method, so I know nothing about any secret, unless I use a privileged function...");
    this.bribe();
  }
}

If you look at what this nets you, you’ll note that it’s really not much different than your example (just using “cleaner” bells and whistles; especially when adding prototype/static methods). It’s still prototype underneath.

If you have the luxury of using any kind of module/export (ES6 being the ideal), then with one other data-type, you can have true privacy and not have to clean up after yourself.

It’s a little hackey-looking. It’ll probably get less ugly, and hopefully be the basis for something cleaner, in the future, but if you want instance-based, private access, even for prototyped methods, then make one WeakMap, inside of the module that you’re exporting your class from.

Use this as your key.
Rather than making privileged functions which have closure access, now all prototype methods have closure access to the weakmap…
…the downside being that any time you want private variables, you have to look them up in the WeakMap rather than pulling them off of / out of this.

const personalBaggage = new WeakMap();

class Person {
  constructor ({ name, age, darkestMoment }) {
    const privates = { name, age, darkestMoment };
    personalBaggage.add(this, privates);
  }

  recallDarkestHour () {
    const { darkestMoment } = personalBaggage.get(this);
    console.log(darkestMoment);
  }
}

export default Person;

As long as you aren’t losing the reference inside of this, this should just work.
Unlike using Symbol, you can’t get a reference to the private object, no matter how hard you try.
If you know the symbols on the object, you can look up the properties using the symbols.
And getting the list of symbols on any object is just a function call away.
Symbol isn’t about keeping things private; it’s about keeping things safe from naming collisions, and defining common symbols that can be used on any object/function, but won’t be picked up in loops, won’t be called or overwritten accidentally, et cetera.

Storing the private bag of data in a weakmap with this as a key gives you access to a completely hidden dataset, which is totally unaccessible outside of that module.
What’s better, the key/value in weakmaps don’t prevent the GC from cleaning them up.
Normally, if they were left in an array, they’d stay there. If the last place an object is used is as a key in a weakmap, then it gets collected and the weakmap value is erased automatically (in native ES6; the memory bonuses can’t be polyfilled, but the object can).

Questions:
Answers:

here is a really good post on the subject. I didn’t know much about doing this in ES6 before your question but after reviewing this it looks really cool. So you create a symbol that is indexed to the function.

here is the code straight from their sit.

var Person = (function() {
    var nameSymbol = Symbol('name');

    function Person(name) {
        this[nameSymbol] = name;
    }

    Person.prototype.getName = function() {
        return this[nameSymbol];
    };

    return Person;
}());

var p = new Person('John');

Private properties in JavaScript

Questions:
Answers:

You may accomplish it using Symbol.

const _name = Symbol();

class Person {
  constructor(name) {
    this[_name] = name;
  } 
}

const person = new Person('John');

alert(person.name);
// => undefined