In fact, you cannot access something private from the prototype.
The prototype works by binding an object as a context to all the methods, so you can use this
keyword to access it.
In Object-Oriented Programming, what you call private is something resolved at compile-time, to hint you that the data you are trying to access is not supposed to be readable from outside the class.
But at run-time this data will be stored the same way as the other properties.
To have methods accessing private fields, you can rather create method on instance directly rather than on prototype to permit it to access private scope.
This is called a privileged method.
Check out this article from Douglas Crockford.
var ClassExample = function () {
var privateProperty = 42
this.publicProperty = 'Hello'
var privateMethod = function () {
return privateProperty
}
this.privilegedMethod = function () {
return privateProperty
}
}
ClassExample.prototype.publicMethod = function() {
return this.publicProperty
}
Languages like Typescript, that add classes and typing + privacy settings store private fields alongside public fields.
class ClassExample {
private privateProperty
public publicProperty
constructor () {
this.privateProperty = 42
this.publicProperty = 'Hello'
}
method () {
return this.privateProperty
}
}
will compile in
var ClassExample = (function () {
function ClassExample() {
this.privateProperty = 42;
this.publicProperty = 'Hello';
}
ClassExample.prototype.method = function () {
return this.privateProperty;
};
return ClassExample;
})();