Reputation: 1211
How can I create a private and static variable in Javascript?
var Class = function() {
this.member = ...; //Public member
var member = ...; //Private member
}
Class.member = ...; //Public static member
//Private static member?
Upvotes: 4
Views: 5374
Reputation: 456
I would use something this:
var Class = (function() {
function Class(){
this.member = ...; // Public member
var member = ...; // Private member
}
Class.member = ...; // Public static member
var member = ...; // Private static member
return Class;
}());
Upvotes: 0
Reputation: 1
var MemberClass = function() {
this.publicmember = 'Public Member'; //Public member
var member = ''; //Private member
MemberClass.staticVar = 'I am a static variable';
this.priviledgedFunction = function() { // Private function
member = 'I am a private variable';
return member;
}
}
Now to access each of those members:
var obj = new MemberClass();
console.log(obj.publicmember) // public member is directly accessible with obj
console.log(MemberClass.staticVar) // To access the static variable
Private members cannot be access directly, but you can access them with something called the priviledged function.
console.log(obj.priviledgedFunction)
Hope this helps!
Upvotes: 0
Reputation: 4571
function InitStatic(init)
{
var _class = this.constructor;
_class._getStatic = function()
{
if(arguments.callee.caller == _class) { return init; }
};
return init;
}
function DemoClass()
{
var _class = this.constructor, _private = { }, _public = this;
_private.Static = _class._getStatic ? _class._getStatic() : InitStatic.call(this, { Prop: "I am static.", Calls: 0 });
_public.Method = function()
{
return ++_private.Static.Calls;
};
}
var a = new DemoClass();
var b = new DemoClass();
console.log(a.Method()); // 1
console.log(b.Method()); // 2 !!
console.log(DemoClass._getStatic()); // undefined
In this solution the static method _getStatic of DemoClass results exact the same object. It's called (and created once) in the constructor function. The "static object" is stored in a private instance variable. So any changes to this object in one instance will effect in each other. The trigger arguments.callee.caller == _class checkes the origin of the method call, to avoid public access.
Upvotes: 1