Private members in CoffeeScript?

后端 未结 11 2059
太阳男子
太阳男子 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:52

    There is one problem with Vitaly's answer and that is you cannot define variables that you want to be unique to the scope, if you made a private name that way and then changed it, the name value would change for every single instance of the class, so there is one way we can solve that problem

    # create a function that will pretend to be our class 
    MyClass = ->
    
        # this has created a new scope 
        # define our private varibles
        names = ['joe', 'jerry']
    
        # the names array will be different for every single instance of the class
        # so that solves our problem
    
        # define our REAL class
        class InnerMyClass 
    
            # test function 
            getNames: ->
                return names;
    
        # return new instance of our class 
        new InnerMyClass
    

    It's not impossible to access the the names array from outside unless you use getNames

    Test this out

    test = new MyClass;
    
    tempNames = test.getNames()
    
    tempNames # is ['joe', 'jerry']
    
    # add a new value 
    tempNames.push 'john'
    
    # now get the names again 
    newNames = test.getNames();
    
    # the value of newNames is now 
    ['joe', 'jerry', 'john']
    
    # now to check a new instance has a new clean names array 
    newInstance = new MyClass
    newInstance.getNames() # === ['joe', 'jerry']
    
    
    # test should not be affected
    test.getNames() # === ['joe', 'jerry', 'john']
    

    Compiled Javascript

    var MyClass;
    
    MyClass = function() {
      var names;
      names = ['joe', 'jerry'];
      MyClass = (function() {
    
        MyClass.name = 'MyClass';
    
        function MyClass() {}
    
        MyClass.prototype.getNames = function() {
          return names;
        };
    
        return MyClass;
    
      })();
      return new MyClass;
    };
    

提交回复
热议问题