Javascript private member on prototype

前端 未结 8 926
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 01:15

Well I tried to figure out is this possible in any way. Here is code:

a=function(text)
{
   var b=text;
   if (!arguments.callee.prototype.get)
      argumen         


        
8条回答
  •  时光取名叫无心
    2020-12-08 01:44

    After being hugely inspired by Christoph's work-around, I came up with a slightly modified concept that provides a few enhancements. Again, this solution is interesting, but not necessarily recommended. These enhancements include:

    • No longer need to perform any setup in the constructor
    • Removed the need to store a public GUID on instances
    • Added some syntactic sugar

    Essentially the trick here is to use the instance object itself as the key to accessing the associated private object. Normally this is not possible with plain objects since their keys must be strings. However, I was able to accomplish this using the fact that the expression ({} === {}) returns false. In other words the comparison operator can discern between unique object instances.

    Long story short, we can use two arrays to maintain instances and their associated private objects:

    Foo = (function() {
        var instances = [], privates = [];
    
        // private object accessor function
        function _(instance) {
            var index = instances.indexOf(instance), privateObj;
    
            if(index == -1) {
                // Lazily associate instance with a new private object
                instances.push(instance);
                privates.push(privateObj = {});
            }
            else {
                // A privateObject has already been created, so grab that
                privateObj = privates[index];
            }
            return privateObj;
        }
    
        function Foo() {
            _(this).bar = "This is a private bar!";
        }
    
        Foo.prototype.getBar = function() {
            return _(this).bar;
        };
    
        return Foo;
    })();
    

    You'll notice the _ function above. This is the accessor function to grab ahold of the private object. It works lazily, so if you call it with a new instance, it will create a new private object on the fly.

    If you don't want to duplicate the _ code for every class, you can solve this by wrapping it inside a factory function:

    function createPrivateStore() {
        var instances = [], privates = [];
    
        return function (instance) {
            // Same implementation as example above ...
        };
    }
    

    Now you can reduce it to just one line for each class:

    var _ = createPrivateStore();
    

    Again, you have to be very careful using this solution as it can create memory leaks if you do not implement and call a destroy function when necessary.

提交回复
热议问题