Implementing private instance variables in Javascript

后端 未结 4 1004
夕颜
夕颜 2020-12-05 03:07

I don\'t know how I\'ve missed this for so long. I\'ve been presuming private instance variables to work like this, but they don\'t. They\'re private (as in non-global), cer

4条回答
  •  暖寄归人
    2020-12-05 03:32

    Privates are expensive, avoid them if possible

    Private doesn't exist. You can do one of two things to emulate this.

    • closures
    • Weakmaps

    Closures

    function makePrinter(word) {
      return {
        print: function () {
          console.log(word)
        }
      }
    }
    

    WeakMap

    Browser support for weakmaps is awful. You will probably need an emulation, I recommend pd.Name

    var Printer = (function () {
      var privates = function (obj) {
        var v = map.get(obj)
        if (v === undefined) {
          v = {}
          map.set(obj, v)
        } 
        return v
      }, map = new WeakMap()
    
      return {
        constructor: function (word) {
          privates(this).word = word
        },
        print: function () {
          console.log(privates(this).word)
        }
      }
    }());
    

    Sensible objects

    var Printer = {
      constructor: function (word) {
        this._word = word
      },
      print: function () {
        console.log(this._word)
      }
    }
    

提交回复
热议问题