Accessing private member variables from prototype-defined functions

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

    see Doug Crockford's page on this. You have to do it indirectly with something that can access the scope of the private variable.

    another example:

    Incrementer = function(init) {
      var counter = init || 0;  // "counter" is a private variable
      this._increment = function() { return counter++; }
      this._set = function(x) { counter = x; }
    }
    Incrementer.prototype.increment = function() { return this._increment(); }
    Incrementer.prototype.set = function(x) { return this._set(x); }
    

    use case:

    js>i = new Incrementer(100);
    [object Object]
    js>i.increment()
    100
    js>i.increment()
    101
    js>i.increment()
    102
    js>i.increment()
    103
    js>i.set(-44)
    js>i.increment()
    -44
    js>i.increment()
    -43
    js>i.increment()
    -42
    

提交回复
热议问题