private
is a really confusing word.
The secret
var you declared using var secret = 3;
is not a 'private' variable. This is a variable that is only visible in the Container constructor scope. And because you declare the method getSecret
in the same scope, it has access to it.
if you had done:
function Container() {
var secret = 3;
}
Container.prototype.getSecret = function() {
return secret;
}
calling getSecret would say that secret is undefined.
And, with your current code, adding:
Container.prototype.getSecret2 = function() {
return this.secret;
}
would return 10. Because your object has now a property called secret
when you do
c1.secret = 10;
But remember:
var secret = 3;
does not attach the variable to the current object. It just create a variable that live in the current scope. Every function declared in that scope will have access to it.