You're right; _name is more of a static variable. It is stored in a closure containing the constructor, so every use of the constructor will use the same variable. And remember that this has nothing to do with classes, and everything related to closure and functions. It can be very convenient, but you are not making private members.
Unsurprisingly, Douglas Crockford has a private members page in Javascript .
To make private members, you need to go "one level deeper." Do not use closure outside the constructor; use the constructor as a closure. Any variables or methods defined inside the constructor, obviously, cannot be used by the outside world. In fact, they are also inaccessible to the object, so they are rather unusual 'private'.
We want to use our private members. :) So what to do?
Well, in the constructor do the following:
var Klass = function () { var private = 3; this.privileged = function () { return private; }; };
and then:
var k = Klass(); console.log(k.privileged());
See how using constructor as a closure? this.privileged lives, attaches to the object, and thus private lives, inside this.privileged closure.
Unfortunately, there is one problem with private and privileged methods in Javascript. Each time they must be created from scratch. No code exchange. It is obvious that we want with private members, but it is not ideal for methods. Using them slows down the creation of objects and uses more memory. This is something to keep in mind when / if you run into performance problems.
source share