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.
class SomeClass
functionName: ->
alert('hello world');
class SomeClass
functionName = ->
alert('hello world');
class Dog
dogName: "fido"
constructor: (@dogName) ->
doStuff: ->
alert('the dog is walking');
sayHello.call(this);
sayHello = ->
alert("Hi! I'm "+@dogName);
ralph = new Dog("ralph");
ralph.doStuff();
peter = new Dog("peter");
peter.doStuff();
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.