Private members in CoffeeScript?

后端 未结 11 2061
太阳男子
太阳男子 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 14:11

    Since coffee script compiles down to JavaScript the only way you can have private variables is through closures.

    class Animal
      foo = 2 # declare it inside the class so all prototypes share it through closure
      constructor: (value) ->
          foo = value
    
      test: (meters) ->
        alert foo
    
    e = new Animal(5);
    e.test() # 5
    

    This will compile down through the following JavaScript:

    var Animal, e;
    Animal = (function() {
      var foo; // closured by test and the constructor
      foo = 2;
      function Animal(value) {
        foo = value;
      }
      Animal.prototype.test = function(meters) {
        return alert(foo);
      };
      return Animal;
    })();
    
    e = new Animal(5);
    e.test(); // 5
    

    Of course this has all the same limitations as all the other private variables you can have through the use of closures, for example, newly added methods don't have access to them since they were not defined in the same scope.

提交回复
热议问题