Private members in CoffeeScript?

后端 未结 11 2060
太阳男子
太阳男子 2020-12-12 13:37

Does somebody know how to make private, non-static members in CoffeeScript? Currently I\'m doing this, which just uses a public variable starting with an underscore to clari

11条回答
  •  盖世英雄少女心
    2020-12-12 13:51

    I'd like to show something even fancier

    class Thing extends EventEmitter
      constructor: ( nm) ->
        _name = nm
        Object.defineProperty @, 'name',
          get: ->
            _name
          set: (val) ->
            _name = val
          enumerable: true
          configurable: true
    

    Now you can do

    t = new Thing( 'Dropin')
    #  members can be accessed like properties with the protection from getter/setter functions!
    t.name = 'Dragout'  
    console.log t.name
    # no way to access the private member
    console.log t._name
    

提交回复
热议问题