Samstag, 9. Januar 2016

[JavaScript] One way to use Object Orientation Programming in JavaScript

It's been a long time since my last post but since i'm working a lot with javascript lately i wanted to tell you my impressions about object oriented programming (OOP) with JavaScript.
For now, none of the javascript projects i did were complex enough to really use OOP. But now i'm working on a pretty complex project so i decided to read a little about JavaScript and its ways to use OOP.

Before getting started i thought about what is important to me if i'm working with objects. The following points came to my mind:

  • Encapsulation: Having the difference between private and public methods is a must have
  • Safety: Public access to attributes only using getters and setters
  • Inheritance: Since i'm trying to follow the DRY (Don't Repeat Yourself) principle i really wanted inheritance to prevent code duplicates

After some research i stumbled upon this neat way to model classes in JavaScript:

function Person() {
 // This attribute can be accessed outside the class
 this.name = "Everyone can see this";
 
 // This attribute cannot be accessed outside the class
 var age;
 
 this.getAge = function() {
  return this.name; 
 }
 
 // This is way more interesting. We can use the private attributes in public methods!
 this.setAge = function(newAge) {
  // We can even acces private function from public functions!
  if (isAgeValid(newAge)) {
   return;
  } else {
   // Here we are setting a new value for the private attribute.
   age = newAge;
  }
 }
 
 // This function is private
 var isAgeValid = function(someAge) {
  return someAge > 0;
 }
}

This is pretty cool, isn't it? But there is still one last topic i need to keep an eye on: the inheritance. Inheritance can be achieved like this:

function Politician() {
 // This is all we need to achieve inhertance
 Person.apply(this, arguments);
 
 var party;
 
 this.setParty = function(newParty) {
  party = newParty;
 }
}

Now we got a politician, which is of course a person. Since it's a person we keep all public attributes and all public function so we can do calls like:

var politician = new Politician();
politician.setAge(-1); // We can call this even though the age is not valid so it won't be set.
politician.setAge(30); // Here we go!
politician.setParty("This could be your party!")

The Downsides

There is not such a thing like protected methods when using this way of inheritance which is okay for me. If you really need protected methods or variables take a look at this one hour presentation by Douglas Crockford

Since the code i'm posting here is just one way to use OOP in JavaScript please let me know in the comments which way you prefer and why.

Cheers,
Loris