JavaScript/OOP-classes

The popularity of class-based programming languages inspires the JavaScript community to cover its prototype-based implementation of OOP with a syntax that mimics a class-based approach. EcmaScript 2015 (ES6) gets expanded by corresponding key words like 'class' or 'extend'.

Classes are templates or 'blueprints' to create objects. They encapsulate their data and contain functions to work on it.

Creation
The keyword  introduces the class definition. In the example, Person is the class name. It is followed by the class body that is enclosed in curly brackets, lines 1 - 11. Within the body, there is a special method. This function is invoked during class creation. In the example, it takes one argument, the name of a person. Within  this argument is stored internally by using the keyword 'this'. The class offers only one functionality: the  method.

Static properties and methods
The above syntax shows how to handle properties and methods of individual objects (instances - like 'ada' in the above example). It's also possible to define properties and methods that are not available at the level of individual objects but at the class level - 'Person' in the above example. They are introduced by the keyword.

Lines 7 and 8 use the 'static' keyword. Therefore the property and method are NOT available for instances, only for the class altogether.

get
Class methods can be offered as properties. This frees the programmer to distinguish between access to methods - via parenthesis  - and properties. The keyword  introduces the feature.

Inheritance
Next, we define a hierarchy of classes. This is done with the keyword. In the example,  is a sub-class of   and has access to all its properties and methods.

Line 12 invokes the constructor of the parent class. This is necessary because the parent's  creates 'this'.

Access control
By default, class properties and methods are accessible. You can hide them by using a hash  as the first character of their name.

Polymorphism
If a method name is used in a 'parent' class as well as in a 'child' class, the JavaScript engine invokes that one of the correlating class.

The example defines and uses two different methods.

this
is not a variable or an object; it's a keyword. Depending on the context, it refers to different things. In the context of class definitions, it refers to the class itself, e.g.,  refers to the property 'city' of the current class.

When  is used at the top level of a file (in other words: outside of any function or object), it refers to the global object. In a function, in strict mode, this is. In a DOM event, it refers to the element that received the event.

Exercises

 * ... are available on another page (click here).