javascript interactive

JavaScript Interactive — a console crash course


5.3 Private Properties

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
function A() {
    this.one = 1;
    this._two = 2;
}

  
>>>
A.prototype.next = function () { return this._two++; };

  
Object properties in JavaScript have no access modifiers (public, private, protected, etc). Instead, it is common practice to prefix "internal" or "hidden" property names with a _ character.
>>>
a = new A()
{ "one": 1, "_two": 2, "next": ... }
Naturally, the properties remain as visible as before. Which is practical when logging or debugging.
>>>
function B() {
    var two = 2;
    this.one = 1;
    this.next = function () { return two++; };
}

  
Using function closures (function scopes), it is possible to hide or protect internals completely. Methods accessing the hidden values must be declared inside the constructor to share the same function scope.
>>>
b = new B()
{ "one": 1, "next": ... }
The value of two is now impossible to access or inspect via the object instance (since it lives in the closure instead).
>>>
b.next()

  
The next() method can still access and modify the private value. But creating hidden properties this way should probably be avoided.

It reduces efficiency of the garbage collector and doesn't take advantage of prototypal inheritance. In general, it adds more complexity than it removes.
>>>

Index 1 2 3 4 5 6 7 8