How to Create Protected Object Properties in JavaScript

前端 未结 8 1938
梦毁少年i
梦毁少年i 2020-12-10 04:49

Is there a JavaScript pattern which mimics \"Protected\" object properties like what you see in languages like C++ ??

Basically, I\'d like to create an Object A whic

相关标签:
8条回答
  • 2020-12-10 05:28

    Take a look at workaround proposed by Maks on his website: Emulating protected members in JavaScript

    It emulates protected access level to methods and properties of an object.

    0 讨论(0)
  • 2020-12-10 05:31

    I found a way for creating protected members. Therefor I call the base constructor and return an object with the protected members at the same time:

    var protected = BaseClass.call(this); 
    

    Here an example:

    function SignedIntegerArray(size)
    {
        var public = this;
        var protected = {};
    
        // private property:
        var _maxSize = 10000;
        // protected property:
        protected.array = [];
        // public property:
        public.Length = size;
    
        if(!isInteger(size) || size < 0 || size > _maxSize) { throw "argument exception"; }
        for(var index = 0; index != size; index++) { protected.array[index] = 0; }
    
        // private method:
        function isInteger(i) { return i == i + 0 && i == ~~i; }
        // protected method:
        protected.checkIndex = function(index) { return index >= 0 && index < size; }
        // public methods:
        public.SetValue = function(index, value) { if(protected.checkIndex(index) && isInteger(value)) { protected.array[index] = value; } };
        public.GetValue = function(index) { if(protected.checkIndex(index)) { return protected.array[index]; } else { throw "index out of range exception"; }}
    
        return protected;
    }
    
    function FloatArray(size, range)
    {
        var public = this;
        var protected = SignedIntegerArray.call(this, size); // call the base constructor and get the protected members 
    
        // new private method, "isInteger" is hidden...
        function isFloat(argument) { return argument != ~~argument; }
        // ...but "checkIndex" is accessible
        public.SetValue = function(index, value) { if(protected.checkIndex(index) && isFloat(value) && value >= public.MinValue && value <= public.MaxValue) { protected.array[index] = value; } };
    
        // new public properties:
        public.MinValue = -range;
        public.MaxValue = range;
    
        return protected; // for sub-classes
    }
    
    function newObject(className, args) { return new function() { className.apply(this, args)}} // you need to use function.call or function.apply to initialize an object. otherwise the protected-object is empty.
    window.addEventListener("load", function()
    {
        var o = newObject(FloatArray, [4, 50.0]);
        o.SetValue(3, 2.1);
        console.log(o.GetValue(3));
        console.log(o.Length); // property from the base-class
    });
    
    0 讨论(0)
提交回复
热议问题