mikelplhts
mikelplhts

Reputation: 1211

How to create a private static variable?

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

Answers (4)

Franz Fankhauser
Franz Fankhauser

Reputation: 139

static #myPrivateStaticMember = 1234;

Upvotes: 0

bugovicsb
bugovicsb

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

pradnya paranjape
pradnya paranjape

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

Martin Wantke
Martin Wantke

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

Related Questions