Developers coming from Java, C#, etc may find JavaScript Object Oriented Programming a bit disconcerting at first;  unlike Java, or C#, JavaScript it is not a class-based language: which means one has to get used to a different way to do things.

Although ECMAScript 6 added class syntax support similar to which we use in other languages, it remains syntactical sugar: underneath it all we are still working with prototype based inheritance. Therefore it is advisable to understand how JavaScript prototypes work.

In this post we will see the basis of object creation, and inheritance using JavaScript constructor functions, and prototypes

JavaScript Constructors

JavaScript constructors are functions that allow us to create objects.

Consider this example in Java:

public class Person {

    public String name;

    public Person(string name) {
        this.name = name;
    }

    public void talk(string message) {
        Sytem.out.println(message);
    }
}

We have a class Person, which has a single attribute name, a constructor Person we will use to create, and initialize our object, and a method talk: all objects of class Person, will have a name, and a method to talk.

Lets see how we could define that same thing, using a JavaScript constructor:

function Person(name) {
        this.name = name;
        this.talk = function (message) {
            console.log(message);
        };
    }

And we would use it like this:

var james = new Person("James");
james.talk("Hello, guys!");

Which would print the message Hello, guys! to the console.

Although the example above works fine, it has a small inconvenient: every time we create an object Person, using the constructor the method talk is recreated.

A more efficient way of defining the same thing would be to make us of the prototype property, like this:

function Person(name) {
        this.name = name;
    }

Person.prototype.talk = function(message) {
    console.log(message);
};
// And usage remains the same as before
var james = new Person("James");
james.talk("Hello, guys!");

The 30 seconds guide to JavaScript Prototype

All JavaScript objects have a prototype property. You can think of it as the object from which other instances are prototyped.

To work with Prototypes, you need to at least  remember this:

  • The methods, and properties we add to a prototype’s object, are available to all instances of that object.
  • When we access a property/method of an object, JavaScript tries to find that property/method in the object itself, if it does not find it, it will try looking for it in the object’ s prototype.

With the points we have just seen we can implement object inheritance.

But before that, lets add a few methods more to our Person prototype:


function Person(name) { this.name = name; }

Person.prototype.talk = function(message) {
  console.log(message);
}; 

Person.prototype.walk = function(miles) {
  console.log(this.name + " walked " + miles +" miles.");
}; 

Person.prototype.eat = function(food) {
  console.log(this.name + " is eating " + food );
}; 

Person.prototype.sleep = function() {
  console.log("Zzzz Zzzzz");
};

The above code can be also written more clearly like this:

 Person.prototype = {
        constructor: Person,

        talk: function(message) {
  			console.log(message);
		},
        walk: function(miles) {
  			console.log(this.name + " walked " + miles +" miles.");
		},
	eat: function(food) {
  			console.log(this.name + " is eating " + food );
		},
	sleep: function() {
		  console.log("Zzzz Zzzzz");
		}
    }

Notice that while in the first example we were adding new methods to the Person‘s prototype object, in the last example we replace the default Person.prototype object with our own custom object: therefore, we must remember to add, on top of the methods we are interested in,  the constructor property of our prototype object.

JavaScript inheritance succinctly

Lets start with our Java example:

class Salesman extends Person
{
   sendEmail(String email, String msg)
   {
      Sytem.out.println("Email send to "+ email);
   }
}

Now lets translate that to JavaScript. First we create the constructor for our Salesman: in our example we want to delegate in the constructor of the parent class:

function Salesman(name){
     Person.call(this, name);
}

Now we need to make it so that Salesman has all the methods that Person has; we can do that if we clone the Person‘s prototype:

Salesman.prototype = new Person();

And finally we need to extend Salesman to have its own methods,
like sendEmail:

Salesman.prototype.constructor = Salesman;
Salesman.prototype.sendEmail= function(email,msg)
    {
       console.log("Email send to "+ email);
    }

Usage:

var peter = new Salesman("Peter");

peter.sendEmail("customer@example.org","Hello");
//output:: Email send to customer@example.org
peter.sleep();
//output:: Zzzz Zzzzz

With that you can get started with JavaScript OOP. Thanks for reading :-). If you found this post useful, you can follow my blog (click at the follow button at the bottom), and be notified when new posts are written.

Advertisements