General concepts

JavaScript is a very flexible language. In contrast with Java, PHP, C++ and many other languages, there are many ways to implement OOP in JavaScript.

So what the OOP is all about? Inheritance is only the small piece.

The three main features should be supported:

Inheritance
It is possible to create a child object TreeMenu which extends functionality of the Menu.

The child object automatically gains access to parent’s methods/properties, but it also can have own methods/properties.

That’s great, because allows to reuse generic Menu code for TreeMenu, SlidingMenu and other specific menu types.

Encapsulation
An object can forbid external access to chosen properties and methods, so that they can only be called by other methods of same object.

That allows to hide internal details of Menu.

For example, the code which uses a Menu should not directly access it’s DOM structure, handler etc. They are internal.

On the other hand, there should be open, hide and other publicly accessible methods. These methods are called an external(or public) interface.

There are three most well-known encapsulation levels:

private
Accessible only from the class itself, not accessible from inheritants.
protected
Accessible from the class itself, inheritants are also allowed to access it.
public
Accessible from anywhere.

Encapsulation helps to support the code, because a programmer always knows, which methods could have been used by the external code, and which can be safely modified or even removed.

Type polymorphism
A code which uses the Menu object can switch to a TreeMenu object or a SlidingMenu without modifications.

It’s possible, because the public interface of Menu is inherited.

In JavaScript, unlike most other languages, there are several syntactically different ways to do implement the OOP concepts described above.

Tutorial

Donate

Donate to this project