Accessing private member variables from prototype-defined functions

前端 未结 25 1394
孤城傲影
孤城傲影 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:37

    You can use a prototype assignment within the constructor definition.

    The variable will be visible to the prototype added method but all the instances of the functions will access the same SHARED variable.

    function A()
    {
      var sharedVar = 0;
      this.local = "";
    
      A.prototype.increment = function(lval)
      {    
        if (lval) this.local = lval;    
        alert((++sharedVar) + " while this.p is still " + this.local);
      }
    }
    
    var a = new A();
    var b = new A();    
    a.increment("I belong to a");
    b.increment("I belong to b");
    a.increment();
    b.increment();
    

    I hope this can be usefull.

提交回复
热议问题