JavaScript Private Variable<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

JavaScript Private Variable

Posted on: May 31, 2017

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

1var MyClass = function (param1, param2) {
2 this.member1 = param1 || ""; // Public
3 var member2 = param2 || ""; // Private
4
5 // Private
6 var function1 = function () {
7 this.member1 = "[" + this.member1 + "]";
8 console.log(this.member1);
9 };
10
11 // Public
12 this.function2 = function () {
13 console.log(member2);
14 };
15};
16
17var x = new MyClass("m1", "m2");
18console.log("Access public member: " + x.member1);
19x.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.

1var MyClass = function (param1, param2) {
2 this.member1 = param1 || ""; // Public
3 var member2 = param2 || ""; // Private
4
5 // Private
6 var function1 = function () {
7 this.member1 = "[" + this.member1 + "]";
8 console.log(this.member1);
9 };
10
11 // Public
12 this.function2 = function () {
13 console.log(member2);
14 };
15};
16MyClass.prototype.function3 = function () {
17 console.log("Function 3 Proto : " + this.member1);
18};
19MyClass.prototype.function4 = function () {
20 console.log("Function 4 Proto : " + this.member2);
21};
22
23var x = new MyClass("m1", "m2");
24x.function3(); // "Function 3 Proto : m1"
25x.function4(); // "Function 4 Proto : undefined"