objects that encapsulate data and behavior.
The simplest way to create our database is to just declare it as a singleton object with some instance data and functions. We’ll use the “starts with underscore” naming convention to denote “private” data but that is just a convention and not enforced.
This is pretty simple and if you try it out you’ll see it actually works.
The biggest downside of this approach is that there is no encapsulation. We can get at the
_data instance variable directly to read or change it.
Encapsulation via a Closure
By wrapping our
Database in a closure we can encapsulate our private functions and data. The way to read this is that
- Database is a function that defines a closure.
- The variables within that closure have access to each other (i.e.
_createhas access to
- When the
Databaseis called it returns an object that explicitly exposes 4 functions and nothing else.
When we test it we see that it still works.
_data is encapsulated and not accessible from the outside