/ javascript

JavaScript and private function/class members

One of JavaScript design flaws is lack of clear private function and class members. There is ways around it and lot's of opinions how stuff should be made. Even some absolutely wrong ideas. Here's simple example of private members.

Thanks for Dr. Axel Rauschmayer and his article Managing the private data of ES6 classes for introducing great way to handle private class properties.

In functions

In functions make property as public with adding it to this. This works with variables and methods. In example id and getMoney() are public. Function getName() is made public with referring it to this.getName afterwards.

Private properties are made with regular defining. In example these are money and name variables. Function getName() is made public by referring to it afterwards.

function Bank() {
  var money = 400;
  this.id = 'FI404404404404404404404';
  var name = 'Joona'

  function getName() {
    console.log(name + ' // ' + this.id);
  }

  this.getName = getName;

  this.getMoney = function() {
    console.log('coins: ' + money);
  }
}

var op = new Bank();
op.getMoney();
op.getName();

If you make prototypes, you can only refer to public variables. Private variables aren't shown in new method's scope.

In Classes

It's more tricky. There is no private properties in classes. Here's a work around which is kind a clean when comparing using another library for this.

In this example private variables are parameters (name & age) of class constructor. Private methods (getName(), addYear() & getAge()) are added to class inside constructor's block scope.

class Puppy {
  constructor(name, age) {
    Object.assign(this, {

        getName() {
          console.log(name);
        },

        addYear() {
          age++;
        },

        getAge() {
          console.log(age);
        }

    });
  }
}

var dog = new Puppy('Roope', 10);
dog.getName(); // Roope
dog.getAge(); // 10
dog.addYear();
dog.getAge(); // 11

Never do

People use a lot underscore in property names to express for other developers that these are meant to be private. Even though they aren't. This is bad way of doing things and also not fixing the problem. Avoid it.