Private members in CoffeeScript?

后端 未结 11 2044
太阳男子
太阳男子 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条回答
  •  Happy的楠姐
    2020-12-12 14:05

    classes are just functions so they create scopes. everything defined inside this scope won't be visible from the outside.

    class Foo
      # this will be our private method. it is invisible
      # outside of the current scope
      foo = -> "foo"
    
      # this will be our public method.
      # note that it is defined with ':' and not '='
      # '=' creates a *local* variable
      # : adds a property to the class prototype
      bar: -> foo()
    
    c = new Foo
    
    # this will return "foo"
    c.bar()
    
    # this will crash
    c.foo
    

    coffeescript compiles this into the following:

    (function() {
      var Foo, c;
    
      Foo = (function() {
        var foo;
    
        function Foo() {}
    
        foo = function() {
          return "foo";
        };
    
        Foo.prototype.bar = function() {
          return foo();
        };
    
        return Foo;
    
      })();
    
      c = new Foo;
    
      c.bar();
    
      c.foo();
    
    }).call(this);
    

提交回复
热议问题