Classes
Learn how to use classes in JavaScript.
Define and use classes
The concept of a class is fundamental in object-oriented (OO) programming. Objects instantiate and are classified by a class. A class defines the properties and methods of the objects created with it.
A class concept is essential to implement a data model in the form of model classes in an MVC architecture. However, classes, their inheritance, and extension mechanisms are overused in classical OO languages such as Java where all variables and procedures have to be defined in the context of a class. Consequently, classes are not only used for implementing object types or model classes, but also as containers for many other purposes in these languages. This is not the case in JavaScript where we have the freedom to use classes for only implementing object types while keeping method libraries in namespace objects.
Any code pattern for defining classes in JavaScript should satisfy five requirements. These requirements are as follows:
- It should allow class names to be defined, a set of instance-level properties (preferably with the option to keep them ‘private’), a set of instance-level methods, as well as a set of class-level properties and methods. It’s desirable that properties can be defined with a range and type, and that they can be defined with other meta-data, like constraints.
- An
is-instance-of
predicate that can be used for checking if an object is a direct or indirect instance of a class. - An instance-level property for retrieving the direct type of an object. In addition, it is desirable to have a third introspection feature for retrieving the direct supertype of a class.
- A property inheritance is required.
- The definition should allow for method inheritance.
In addition, it’s a good ...