Coffeescript Classes and Public / Private functions

So I’ve seen some coders confused by how they should declare their functions in Coffeescript. Here’s some notes I took while learning on how to make the equivilant of Public and Private functions for your class in Coffeescript. Because of the way javascript works it’s not possible to have private functions in the way you’re used to with C / Java howevever you can come close.

Public Function – This is your bread and butter function, it is what most coders use by default with coffeescript and is accessible from outside the class.  Notice how it uses a colon after the function name instead of an equals sign.

class SomeClass
functionName: ->
alert('hello world');        

Private function – This will create a private function as it makes the function a variable inside the class. So the function is a closure and can only be accessed by functions of that class. Notice how it uses an equal sign instead of a colon.

class SomeClass
functionName = ->
alert('hello world');

There are two catches with Private Functions. The first is because they are a completely seperate function the @ (this) variable will not point to the main object (even though it is called from another internal function). If you wish to use @ in a private function whenever you call the private function it you must use .call(this) which will load the function but use the main class object as the @ variable inside it. For example:

class Dog
dogName: "fido"
constructor: (@dogName) ->

doStuff: ->
alert('the dog is walking');;

sayHello = ->
alert("Hi! I'm "+@dogName);

ralph = new Dog("ralph");

peter = new Dog("peter");

If you run this example yourself you’ll notice both dogs have separate names and have the private function sayName. The sayName function cannot be called from outside the class (if you try and call it you’ll get an error) which is exactly how private functions should work.

The second catch is that this private function is shared for every dog. This isn’t really an issue for private functions as whenever you use @ the @ variables are specific to each dog. Though it is an issue if you wish to create private variables for your dog, as if you create them in this way they will be shared between every dog which is most likely not what you want.

If you have any questions or queries let me know via the contact form.