Object-Oriented JavaScript – Part II (encapsulation)
To carry on our tutorial on object oriented JavaScript, as our next step will be on encapsulation.
What is encapsulation? Gary Booch defined encapsulation as “the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation.” Sounds smart eh?
So let’s dummy it down for this example. I’m sure you noticed, and I hope you asked yourself, in our previous examples, what if someone used a method that was being used with one object with another, well that methods scope would be over written by the new one. To ensure that each object can have it’s own method, we would have to write the method in the scope of the object. Did you “whuh?” there again? Maybe a code example will help.
var Person = {
name : 'Shawn',
getName : function() {
return this.name;
}
};
Now we have a function inside an object variable! However we should look at the Person variable as the object and the getName function the method inside the object. So now, if we had another object that used the same method name we would do the same thing for the other object.
Now with this example we don’t have to instantiate the new object we can simply run:
alert(Person.getname());
and we should be returned with the Person objects name. However should we want to change the name of the Person, we can do the following:
Person.name = 'Erin'; alert(Person.getName());
With this we should return the name ‘Erin’.
I should mention that this process of having variable.method() pattern is called namespacing. Namespacing is important in making your code more readable as each method will have a namspace assigned to it, thus making encapsulation work and limits the scope of methods to it’s object namespace.
While this posting was short, it is important to note the importance of encapsulation, where it applies. It can clean up your code and it can help with ensuring your code is run in it’s own local scope.








![Validate my RSS feed [Valid RSS]](http://www.unemployeddeveloper.com/wp-content/themes/ud2/images/valid-rss.png)
[...] This post was mentioned on Twitter by Miguel Trindade Jr and Unemployed Developer. Unemployed Developer said: Unemployed Developer: Object-Oriented JavaScript – Part II (encapsulation) http://bit.ly/XH0YX [...]
alert(Person.getname()); // getName
@-RB – whoops! Syntax error! Good eye.
[...] wanted to write a simple and quick tutorial taking our initial Object Oriented JavaScript postings( Object-Oriented JavaScript – Part II (encapsulation) & Object-Oriented JavaScript – Part I (Objects)) and expand on them using [...]