Created
March 22, 2012 04:39
-
-
Save rondale-sc/2155999 to your computer and use it in GitHub Desktop.
encapsulation-in-javascript.js
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
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." |
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
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