Skip to content

Instantly share code, notes, and snippets.

@mikekunze
Created October 19, 2013 14:42
Show Gist options
  • Save mikekunze/7056806 to your computer and use it in GitHub Desktop.
Save mikekunze/7056806 to your computer and use it in GitHub Desktop.
The concept of closures in javascript is important to understand because you might not even know you're doing it. If you write in coffee-script classes or do classical inheritance patterns in vanilla javascript, you are using closures. The following example is a starting point for classical inheritance in javascript. This shows how to hide priva…
function car() {
// Private Variable
var val = {
make : "generic",
model : "generic",
color : "generic"
};
// "new" instance
return {
setMake: function(newMake) {
make = newMake || "generic";
val.make = make;
},
getMake: function() {
return val.make;
},
setModel: function(newModel) {
model = newModel || "generic";
val.model = model;
},
getModel: function() {
return val.model;
},
setColor: function(newColor) {
color = newColor || "generic";
val.color = color;
},
getColor: function() {
return val.color;
},
self: function() {
return val;
}
}
}
// Create our instances
var juke1 = car();
var juke2 = car();
// Set make
juke1.setMake("nissan");
juke2.setMake("nissan");
// Set model
juke1.setModel("juke");
juke2.setModel("juke");
// Set color
juke1.setColor("red");
juke2.setColor("black");
// Cannot get private variable, cool!
juke1.val // undefined
juke2.val // undefined
// Use getter for access to private data
juke1.self() // Object {make: "nissan", model: "juke", color: "red"}
juke2.self() // Object {make: "nissan", model: "juke", color: "black"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment