Understanding the Javascript prototype and OO

It’s something that I’ve run into today and I thought might be interesting for others.

The following issues were raised:

  • How to understand that Javascript is actually object-oriented?
  • What is the role of prototype in Javascript?

First, let’s see why JS is object oriented. Suppose you have a function like this:

myFunc = function() { alert(‘Hi’);};

When this is executed, Javascript will actually create a class called ‘myFunc’ with a static default method inside. How to understand this?? Well, just keep in mind, that you could have implemented the function this way:

myFunc = function(greeting) {
this.myMessage = greeting;

Then create two instances like this:
myFirstFuncInstance = new myFunc(‘Hi’); //Hi
mySecondFuncInstance = new myFunc(‘Hello’);//Hello

alert(myFirstFuncInstance.myMessage); //Hi
alert(mySecondFuncInstance.myMessage); //Hello

You could have of course invoked only the function itself, like this:
myFunc(‘Hello world’); //Hello World

So, as you may have noticed, besides the fact of acting as the default method for the class (the method invoked upon “myFunc(‘Hello world’)”), the function also acts as a constructor for the newly created instances.

That would be it for the idea of how OO design works in Javascript.

Now, second, let’s see how the prototype fits in. Well, speaking in Java terms, prototype is a utility to add properties to the class at runtime. So, given the previous statements, if you’d like to add a behaviour to all the instances of myFunc, you’d like to write something like this:

myFunc.prototype.wrappedGreeting = function (name) {
alert(this.myMessage + ‘ ‘ + name);
myFirstFuncInstance.wrappedGreeting(‘Joe Doe’); //Hi Joe Doe
mySecondFuncInstance.wrappedGreeting(‘Joanne Doe’); //Hello Joanne Doe

alert(‘I hope this was useful and wish you good luck ;)’);


It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply