×
Get in touch

Get in touch with Binary

Binary Studio website uses cookies to enhance your browsing experience. By continuing to use our site, you agree to our Privacy Policy and use of cookies.

Learn more more arrow
Agree
Binary Studio 28.09.2011

Object-Oriented Programming in JavaScript and several methods to implement it


This article describes OOP (methods of encapsulation, polymorphism and inheritance) in JavaScript. We will review two approaches to build it (with prototypes and without). Also I will show how to build a class factory.

So, let's get started

1. OOP building with “Prototypes”

At first we need to have an object…

Now we need to create a child to show inheritance. We will do it with property “prototype”.

Now I will show how to implement inheritance where class is used instead of object:

So methods, as we see, are stored in the prototype.

In code below we will show how to implement polymorphism with prototypes:

In code above we see that we call parent method “clickOnMe” from class prototype;

Encapsulation:

 

2. OOP building without “Prototypes”

The logic of work without prototypes is the same, but you will notice that initialization of methods is in constructor. So here is an example:

 

Encapsulation without prototypes can be implemented in initialization of variables and methods inside constructor and if you want to make method or action public you need to set link of the current object for this method or property, example:

Polymorphism without “Prototypes” can be implemented by overriding link for parent method from the child. Let’s take a look:

3. Class factory

Now at the end let me show you how to create class factory in JavaScript:

Inheritance and polymorphism in class factory:

Summary:

So OOP with prototypes:

1)   Works faster;

2)   Doesn’t take a lot of memory;

3)   Works with “instanceof” statement (tests if an object is of a particular type. It evaluates to true if the object is that type and false if it is not. Instance of is a reserved word and cannot be used for anything else but testing the object's type).

Benefits of method without prototypes:

1)   Can create private members (properties and functions);

My point of view is that the first method is better, because it works faster and looks more reliable as good code structure. But benefits of method without prototype are also important, for example if we don’t want to rely only on agreements for JavaScript (i.e. _protectedMethod).

Benefits of class factory:

Class factory is very similar on “OOP without prototypes” but looks much better and we don’t need to put additional word “new” when we create an object. i.e. button1 = Button(‘b’). And structure of code is much better. But general performance is less than in “OOP with prototypes”.

 

Sergey K., .NET team,

Binary Studio