- Posted by liammclennan on February 18, 2011
I recently described some of the patterns used to simulate classes (types) in JavaScript. But I missed the best pattern of them all. I described a pattern I called constructor function with a prototype that looks like this:
and I mentioned that the problem with this pattern is that it does not provide any encapsulation, that is, it does not allow private methods.
Now we have prototypal inheritance and encapsulation. The important thing to understand is that the constructor, and the toString function both have access to the name and age private variables because they are in an outer scope and they become part of the closure.