The word ‘private’ is never mentioned on CoffeeScript.org and the CoffeeScript Style Guide suggests that we prefix methods with an underscore in order to declare them as private. Of course, doing this doesn’t really make them private - it just means you are naming them with an underscore.
While the private method and variables is indeed private, our
greet method doesn’t work as expected (it returns ‘Hi, Mr’ instead of ‘Hi, Mr Bob’) - the
The two private members can only be accessed within the closure of the
Person instance, but because the scope of
this is wrong, the private function doesn’t have access to any public instance members - which really sucks. You can get around this by explicitly doing
salutation.call(this), but this seems really weird - having to call public and private functions in two different ways seems like a bad idea. Furthermore these private functions will also not be inherited.
The private variables are even worse though. Consider this example:
What happened? Why do both users suddenly have this same name? This is because the private variables are actually shared between all instances of the User ‘class’. So private variables are basically a no-go.
Bottom line - stick with the convention of naming private members with a leading underscore. Private members just don’t work all that well. Happy coding.