Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private members in CoffeeScript?

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"?

like image 205
thejh Avatar asked Jan 13 '11 21:01

thejh


People also ask

How do I declare a variable in CoffeeScript?

In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.

How do you write a function in CoffeeScript?

To define a function here, we have to use a thin arrow (->). Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in JavaScript as shown below. (function() {}); It is not mandatory to use the return keyword in CoffeeScript.


1 Answers

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); 
like image 155
Vitaly Kushner Avatar answered Oct 08 '22 11:10

Vitaly Kushner