Skip to content

Instantly share code, notes, and snippets.

@rmosolgo
Last active January 3, 2016 07:19
Show Gist options
  • Save rmosolgo/8428972 to your computer and use it in GitHub Desktop.
Save rmosolgo/8428972 to your computer and use it in GitHub Desktop.
Private variables and methods in JavaScript and CoffeeScript
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
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
@rmosolgo
Copy link
Author

@danielmurphy points out the the "class definition" has to return this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment