Created
August 17, 2012 00:47
-
-
Save EvanHahn/3374882 to your computer and use it in GitHub Desktop.
Private members don't really work in CoffeeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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