Skip to content

Instantly share code, notes, and snippets.

@EvanHahn
Created August 17, 2012 00:47
Show Gist options
  • Save EvanHahn/3374882 to your computer and use it in GitHub Desktop.
Save EvanHahn/3374882 to your computer and use it in GitHub Desktop.
Private members don't really work in CoffeeScript
// This is an example in a post about private members in CoffeeScript.
// Read more: http://evanhahn.com/?p=1126
var Animal, birch, jambo;
Animal = (function() {
var firstName;
firstName = "";
function Animal(n) {
firstName = n;
}
Animal.prototype.getFirstName = function() {
return firstName;
};
return Animal;
})();
jambo = new Animal("Jambo");
console.log(jambo.getFirstName());
birch = new Animal("Birch");
console.log(birch.getFirstName());
console.log(jambo.getFirstName());
// This is the output of the following:
/*
class Animal
firstName = "" # Private member
constructor: (n) ->
firstName = n
getFirstName: ->
firstName
jambo = new Animal "Jambo"
console.log jambo.getFirstName() # => "Jambo"
birch = new Animal "Birch"
console.log birch.getFirstName() # => "Birch"
console.log jambo.getFirstName() # => "Birch" # Not what we want!!
*/
// This code by Evan Hahn (evanhahn.com) is licensed under the Unlicense.
// http://unlicense.org/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment