Private members in CoffeeScript?

thejh picture thejh · Jan 13, 2011 · Viewed 29.2k times · Source

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 clarify that it shouldn't be used outside of the class:

class Thing extends EventEmitter
  constructor: (@_name) ->

  getName: -> @_name

Putting the variable in the class makes it a static member, but how can I make it non-static? Is it even possible without getting "fancy"?

Answer

Vitaly Kushner picture Vitaly Kushner · Dec 1, 2011

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);