Skip to content

Instantly share code, notes, and snippets.

@rondale-sc
Created March 22, 2012 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondale-sc/2155999 to your computer and use it in GitHub Desktop.
Save rondale-sc/2155999 to your computer and use it in GitHub Desktop.
encapsulation-in-javascript.js
function Mammal(species, defining_characteristic) {
this.species = species;
this.defining_characteristic = defining_characteristic;
}
Mammal.prototype.print = function(){
return "Hello I'm a " + this.species + ". " +
"I have " + this.defining_characteristic + "."
}
var cat = new Mammal("Cat", "claws");
var dog = new Mammal("Dog", "a wet nose")
console.log(cat.print());
// "Hello I'm a Cat. I have claws."
console.log(dog.print());
// "Hello I'm a Dog. I have a wet nose."
var Mammal = (function(){
// These are private
var species;
var defining_char;
return {
// These are public because of the explicit return
init: function (sp, dc) {
species = sp;
defining_char = dc;
},
print: function() {
return "Hello I'm a " + species + ". " +
"I have " + defining_char + ".";
}
};
});
// cat = Mammal(); cat.init("Cat", "claws"); cat.print();
// "Hello I'm a Cat. I have claws."
// dog = Mammal(); dog.init("Dog", "a wet nose"); dog.print();
// "Hello I'm a Dog. I have a wet nose."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment