How to create private variable accessible to Prototype function?

前端 未结 4 1349
陌清茗
陌清茗 2020-12-08 01:35

I\'m trying to get a deeper hold on prototypal inheritance and class creation (I know, there are other ways, but for the purpose of this I\'m trying to grasp prototypes.) My

4条回答
  •  自闭症患者
    2020-12-08 01:58

    It can be easily achieved like this

    function SharedPrivate(){
      var private = "secret";
      this.constructor.prototype.getP = function(){return private}
      this.constructor.prototype.setP = function(v){ private = v;}
    }
    
    var o1 = new SharedPrivate();
    var o2 = new SharedPrivate();
    
    console.log(o1.getP()); // secret
    console.log(o2.getP()); // secret
    o1.setP("Pentax Full Frame K1 is on sale..!");
    console.log(o1.getP()); // Pentax Full Frame K1 is on sale..!
    console.log(o2.getP()); // Pentax Full Frame K1 is on sale..!
    o2.setP("And it's only for $1,795._");
    console.log(o1.getP()); // And it's only for $1,795._
    

    Obviously the key point is to create an access route to a private variable by utilizing a closure and then sharing this access point among the objects to be created. Utilizing the access point as a prototype of the objects to be created for natural sharing is the ideal case. Accordingly the same functionality can be achieved by utilizing the factory pattern and Object.create() as follows;

    function SharedPrivate(){
    var priv = "secret";
    return {gp : function(){return priv},
            sp : function(v){priv = v}
           }
    }
    sharedProto = SharedPrivate(); // priv is now under closure to be shared
    var p1 = Object.create(sharedProto); // sharedProto becomes o1.__proto__
    var p2 = Object.create(sharedProto); // sharedProto becomes o2.__proto__
    

    JavaScript prototypical structure is golden..!

提交回复
热议问题