如何创建私有静态变量

时间:2015-09-23 10:50:59

标签: javascript variables static private

如何在Javascript中创建私有和静态变量?

var Class = function() {
    this.member = ...; //Public member
    var member = ...; //Private member
}

Class.member = ...; //Public static member

//Private static member?

4 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

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

在此解决方案中,DemoClass的静态方法_getStatic与对象完全相同。它在构造函数中被调用(并创建一次)。 “静态对象”存储在私有实例变量中。因此,在一个实例中对此对象的任何更改都将相互影响。触发器 arguments.callee.caller == _class 检查方法调用的来源,以避免公共访问。

答案 2 :(得分:0)

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;
    }
}

现在访问每个成员:

var obj = new MemberClass();
console.log(obj.publicmember) // public member is directly accessible with obj
console.log(MemberClass.staticVar) // To access the static variable

私人成员无法直接访问,但您可以使用称为特权函数的内容访问它们。

console.log(obj.priviledgedFunction)

希望这有帮助!

答案 3 :(得分:0)

我会用这个:

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;
}());