Skip to content

Instantly share code, notes, and snippets.

@jlem
Last active November 11, 2015 21:13
Show Gist options
  • Save jlem/69d0b93a32d1a3e02cc8 to your computer and use it in GitHub Desktop.
Save jlem/69d0b93a32d1a3e02cc8 to your computer and use it in GitHub Desktop.
Encapsulation in JS
class Person {
constructor(age) {
this.age = age;
}
}
let person = new Person(15);
person.age = -33;
// This lack of encapsulation and privacy is bad since it makes
// it easy to use an object in an illegal way.
//
// The result will be more frequent runtime bugs and more defensive programming
// to account for undesirable state
// Consider this alternative
function Person(age) {
// Implicit private state from params,
// or pass in a state object and track it here as a var.
// Hoise your public API up here (just using ES6 shorthand here)
return {
incrementAge,
getAge
};
// Implementation of your API down here
function incrementAge() {
age++;
}
function getAge() {
return age;
}
}
let person = Person(15);
person.incrementAge();
person.getAge(); // 16
person.age // undefined
// Unfortunately, you can still do this:
person.age = -33;
person.age; // 33;
// But while the above is still illegal usage,
// at least this doesn't affect the actual internal state referenced by the API:
person.getAge(); // still 16.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment