Updated: This is an update to my previous question that was somewhat off topic as to what this StackExchange is aiming for. But I have a follow up question to the previous inquiry about this subject.
Object Model:
var Soldier;
Soldier = (function() {
"use strict";
function Soldier() {
var privateVar = "privateValue";
this.methodToGetPrivateValue = function() {
return privateVar;
}
}
var sharedPrivateVar = "sharedPrivateValue";
function sharedPrivateMethod() {
// I want to get value `privateVar`
}
Soldier.prototype = {
publicVar: "publicValue",
publicMethod: function() {
return this.publicVar;
},
sharedPrivate: function() {
return sharedPrivateVar;
}
}
return Soldier;
})();
var marine = new Soldier();
So my updated question to make this topic more a proper question is if there is anyway to get a sharedPrivateMethod defined in this way to be able to access the private variable in the above setup?
The reason I am asking is that the sharedPrivateMethod is totaly invisible to the instanced object. While the function defined inside Soldier() is accessible to the instance because of the this.method = function(). I dont know if it has any real use at the moment but would be interesting to see if it was possible somehow.
The problem with what you have there is that your
_selfvariable is shared by all instances constructed vianew Test, and so for instance, assume yourprivateMethodused it:Then this:
…would log “Message 2”, not “Message 1” as you would expect, because the second call to
new Testhas overwritten the_self_variable.Other than the
_selfvariable, what you have is fine. It lets you have private data and functions shared by all instances, which is very handy. If you need to have truly private data that’s specific to each instance, you need to create the function that uses that data in the constructor function itself:Then
trulyPrivateis genuinely private to the instance. The cost is the cost of creating ashowTrulyPrivatefunction for each instance. (The function objects may be able to share the underlying code, a good engine will do that, but there will be separate function objects.)So to wrap up: