Accessing private member variables from prototype-defined functions

前端 未结 25 1243
孤城傲影
孤城傲影 2020-11-22 14:48

Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var priv         


        
25条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 15:18

    There is a very simple way to do 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._
    

    JavaScript prototypes are golden.

提交回复
热议问题