Last active
January 3, 2016 07:19
-
-
Save rmosolgo/8428972 to your computer and use it in GitHub Desktop.
Private variables and methods in JavaScript and CoffeeScript
This file contains 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
Submarine = -> | |
# "private", within function scope but not attached to the new instance | |
secretWeapon = "missiles" | |
fireSecretWeapon = -> console.log "fire ze " + secretWeapon | |
# "public", attached to the new instance | |
@reveal = -> secretWeapon | |
@setWeapon = (weapon) -> | |
secretWeapon = weapon | |
@fire = -> fireSecretWeapon() | |
@ | |
nuclear_submarine = new Submarine | |
dolphin_submarine = new Submarine | |
dolphin_submarine.setWeapon "dolphins" # update the "private" var | |
console.log nuclear_submarine.fire() # => fire ze missiles! | |
console.log dolphin_submarine.fire() # => fire ze dolphins! | |
# "Private" functions & vars are "private" | |
dolphin_submarine.secretWeapon # => undefined | |
dolphin_submarine.fireSecretWeapon # => undefined |
This file contains 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
Submarine = function() { | |
// "private", within function scope but not attached to the new instance | |
var secretWeapon = "missiles"; | |
var fireSecretWeapon = function() { | |
return console.log("fire ze " + secretWeapon); | |
} | |
// "public", attached to the new instance | |
this.reveal = function() { | |
return secretWeapon; | |
}; | |
this.setWeapon = function(weapon) { | |
return secretWeapon = weapon; | |
}; | |
this.fire = function() { | |
return fireSecretWeapon() | |
}; | |
return this; | |
}; | |
nuclear_submarine = new Submarine; | |
dolphin_submarine = new Submarine; | |
dolphin_submarine.setWeapon("dolphins"); // update the "private" var | |
console.log(nuclear_submarine.fire()) // => fire ze missiles! | |
console.log(dolphin_submarine.fire()) // => fire ze dolphins! | |
// "Private" functions & vars are "private" | |
dolphin_submarine.secretWeapon // => undefined | |
dolphin_submarine.fireSecretWeapon // => undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@danielmurphy points out the the "class definition" has to return
this