Patrick Desjardins Blog
Patrick Desjardins picture from a conference

JavaScript Private Variable

Posted on: 2017-05-31

Defining a private variable is a matter of using var instead of this. This is true with every kind of members: variables or functions.

var MyClass = function (param1, param2) {
  this.member1 = param1 || ""; // Public
  var member2 = param2 || ""; // Private

  // Private
  var function1 = function () {
    this.member1 = "[" + this.member1 + "]";
    console.log(this.member1);
  };

  // Public
  this.function2 = function () {
    console.log(member2);
  };
};

var x = new MyClass("m1", "m2");
console.log("Access public member: " + x.member1);
x.function2();

The code above works, but if you try to access member2 you will get undefined. If you try to access function1, you will get an exception that the function doesn't exist.

In the following, code we introduce prototype function. While there is many advantages like that the function will be shared in memory across all instances. However, one drawback is that you cannot access private members of the class. In the example below, the function4 doesn't work because it tries to access a member initialized with var.

var MyClass = function (param1, param2) {
  this.member1 = param1 || ""; // Public
  var member2 = param2 || ""; // Private

  // Private
  var function1 = function () {
    this.member1 = "[" + this.member1 + "]";
    console.log(this.member1);
  };

  // Public
  this.function2 = function () {
    console.log(member2);
  };
};
MyClass.prototype.function3 = function () {
  console.log("Function 3 Proto : " + this.member1);
};
MyClass.prototype.function4 = function () {
  console.log("Function 4 Proto : " + this.member2);
};

var x = new MyClass("m1", "m2");
x.function3(); // "Function 3 Proto : m1"
x.function4(); // "Function 4 Proto : undefined"