Javascript private member on prototype

前端 未结 8 923
没有蜡笔的小新
没有蜡笔的小新 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 02:01

    Personally, I don't really like the solution with the guid, because it forces the developer to declare it in addition to the store and to increment it in the constructor. In large javascript application developers might forget to do so which is quite error prone.

    I like Peter's answer pretty much because of the fact that you can access the private members using the context (this). But one thing that bothers me quite much is the fact that the access to private members is done in a o(n) complexity. Indeed finding the index of an object in array is a linear algorithm. Consider you want to use this pattern for an object that is instanciated 10000 times. Then you might iterate through 10000 instances each time you want to access a private member.

    In order to access to private stores in a o(1) complexity, there is no other way than to use guids. But in order not to bother with the guid declaration and incrementation and in order to use the context to access the private store I modified Peters factory pattern as follow:

    createPrivateStore = function () {
    var privates = {}, guid = 0;
    
    return function (instance) {
        if (instance.__ajxguid__ === undefined) {
            // Lazily associate instance with a new private object
            var private_obj = {};
            instance.__ajxguid__ = ++guid;
            privates[instance.__ajxguid__] = private_obj;
            return private_obj;
        }
    
        return privates[instance.__ajxguid__];
    }
    

    }

    The trick here is to consider that the objects that do not have the ajxguid property are not yet handled. Indeed, one could manually set the property before accessing the store for the first time, but I think there is no magical solution.

    0 讨论(0)
  • 2020-12-08 02:07

    I have created a new library for enabling private methods on the prototype chain. https://github.com/TremayneChrist/ProtectJS

    Example:

    var MyObject = (function () {
    
      // Create the object
      function MyObject() {}
    
      // Add methods to the prototype
      MyObject.prototype = {
    
        // This is our public method
        public: function () {
          console.log('PUBLIC method has been called');
        },
    
        // This is our private method, using (_)
        _private: function () {
          console.log('PRIVATE method has been called');
        }
      }
    
      return protect(MyObject);
    
    })();
    
    // Create an instance of the object
    var mo = new MyObject();
    
    // Call its methods
    mo.public(); // Pass
    mo._private(); // Fail
    
    0 讨论(0)
提交回复
热议问题