Quick Tutorial: Javascript Object-Oriented Programming For OO Programmers

So you’re already familiar with Object-Oriented Programming concepts. You’re also comfortable writing programs the Object-Oriented way, either using C++, Java, PHP, Ruby, and other OO languages. Now you want to learn Object-Oriented Javascript, but can’t quite figure the sh*t out on how the hell Javascript implements OOP. Behold! This tutorial is for you man!

Like any OOP tutorials out there, Let us start by declaring a class.

function Car() { }

“b*tch! That’s a function! Show me how to create a class!”

I’m not kidding you bro!! With that normal function you just created, in some way, a class. Actually, we can say that the function above is the constructor or initializer of the Car class. You know, the very first method that is executed every time you instantiate an object of that class. In Javascript, there is a convention wherein a constructor function must start with a capital letter, to easily identify constructor function with a normal function. With that blank function we can already create Car objects.

var my_car = new Car();

Of course, we can also add some property initialization on the Car constructor.

function Car(color) {
  this.color = color;
}

var my_car = new Car("red");

A little review for you. In this context, this refers to the current object that was initialized by the constructor. However, let me leave you with this warning about the this variable: Some Javascript libraries such as JQuery overrides this variable in a peculiar way that adds confusion and complexity to everyone’s head..

“Where does the color property came from?”

If you are asking this question, I think you need to review the basics of the language bro. Javascript is a dynamic language. That means you can create things on the fly. You don’t need to declare them, you can just use them immediately.

my_car.owner = "Harry Potter";  // creates an owner property on the fly

Now let us add a method to our Car class.

Car.prototype.run = function(){
  alert(this.color + " car is about to run.");
  alert("Vrooooom!!");
}

“Wait..What? What the hell just happened?!”

Okay. Here’s one of the things that makes OOP on Javascript weird. Javascript is not your usual Object-Oriented Language. Rather it belongs to a subclass of OOP called Prototype-Based Programming.

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming.

Let me put it in simpler explanation.

A Prototype

In usual OO Languages like C++ and Java, we declare class to act as the blueprint of the class objects. Like a blueprint, class describes what a real car must look like. On the other hand, in Prototype-based programming, we don’t use blueprints. We create a real object that will be copied every time we create an object, which is called a prototype. It is a real car, and we can say that all the created cars are its clones.

Again, let me say it: A prototype is an object.

Here’s the complete prototype definition of a Car with added fields and methods.

// Constructor
function Car(color) { 
  this.color = color;
}

// Prototype Fields
Car.prototype.owner = "Anonymous";
Car.prototype.transmission = "Manual";

// Prototype Methods
Car.prototype.run = function(){
  alert(this.color + " car is about to run.");
  alert("Vrooooom!!");
}

Car.prototype.stop = function(){
  alert("STOP");
}

Basically, this is how Javascript implements Object-Oriented Programming. It doesn’t have classes, instead prototypes that will serve as the model for the objects. With that prototype already defined, we can already create and use Car objects like this:

var my_car = new Car("red");

alert(my_car.owner);         // outputs "Anonymous"
my_car.transmission = "Automatic";

my_car.run();                // outputs "red car is about to run.", "Vrooooom!"

That’s it. You are now equipped to do some sh*ts! Get your hands dirty and begin to play some Javascript OOP!

Hey bro! Wait. All the information presented here are just the basics. My sole purpose here is to give you a quick and easy introduction on how OOP works on Javascript. Here are some of my recommended readings:

https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/

If you want to be a hardcore Javascript programmer, you can check this thread.

Goodluck on your Javascript career! :)

>

8 Comments

  • January 15, 2012 - 1:34 am | Permalink

    Thanks! Magagamit ko to. btw anong ginamit mo sa pag insert nung code sa post?

    • Karl Paragua
      January 15, 2012 - 10:33 am | Permalink

      Google Syntax Highlighter! Not sure if there is a plugin for blogger/blogspot though

  • January 15, 2012 - 3:01 pm | Permalink

    I should start working on objects. :)

  • January 19, 2012 - 10:03 am | Permalink

    wow this is great! hahaha.. I never tried usin Javascript for OOP simply because it relies on the client side. Usually, I’m just using this for aesthetic of my UI and leave all the logic behind on the server side scripts (whatever I’m using).

    Though, one best way of using this is if you implement a HTML/AJAX application via Adobe AIR. This OOP way might be very very helpful.

    Thanks for this! Great post!

    • Karl Paragua
      January 21, 2012 - 1:01 pm | Permalink

      I also never faced a situation wherein using OOP in Javascript is the best way. Maybe I didn’t encounter those kind of projects yet. But still this knowledge will still come in handy in the future. :)

  • seb
    March 10, 2012 - 7:11 am | Permalink

    This is the first example that is simple and works. Not a huge fan of the slang but it’s useful regardless so thanks for the effort!

    • Karl Paragua
      March 24, 2012 - 2:53 pm | Permalink

      Thank you for dropping by seb. I hope you’ve learned something.

  • Alex Sales
    May 8, 2012 - 10:18 am | Permalink

    Nice tutorial!

  • Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.