5 Guys The Evolution Of Classes In Javascript Part 1
I’m demonstrating a few patterns for creating objects in JavaScript. We often want to make objects to organize functionality, provide context for our methods, and encapsulate data. To demonstrate this, I will show five different versions of the Guy class with the same basic capabilities: store (“keep”) “stuff” and “show” stuff without sharing it. I’m using the analogy of a guy named bob to help people not familiar with object-oriented JavaScript keep their bearings.
First, I made a basic closure around an object literal so I can pass in some variables during instantiation: (GUY1)
Running this code in the console will allow you to see that Bob keeps a pair of socks in box zero:
Once he keeps the socks, he won’t share them (he will not pass the sock object back), only show a JSON representation of his socks. In Netbeans, we can see that our constructor function is accurately identified as a class:
However, it’s not obvious that bob is an instance of Guy because we didn’t use the “new” operator. We have another problem with Bob. Despite the fact that we told him not to share his socks with others, his socks are not encapsulated–anyone can take them or change them:
While Bob may not care too much if someone else wears his socks, he would care in this scenario:
Someone who knew where Bob keeps his cash was able to set him to zero dollars. Sad Bob.