According to Wikipedia, Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).
Object — Book
Properties — Title, Price, Author, Year of Publication
Methods — Buy, Read, Review
The concepts of OOP can be broken down into the following:
- Object Literals
- Constructor (ES5)
- Object Create Method
- Classes (ES6)
We can call an individual property by using the dot or bracket notation.
Creating a large number of objects with the same properties and methods using the object literals would be a pain, time-consuming and cumbersome task. Hence, constructors come in. Constructor is basically just a function.
Using constructor, it would be written as:
Instantiate an object simply means creating bookOne and bookTwo as an instance of object Book.
Prototypes allow you to easily define methods to all instances of a particular object. For example, to get the age of the book, we can define getAge method as below:
We can also change or revise the year of publication by:
Lets create a magazine that inherits the properties of a book.
Object Create Method
The Object.create() method creates a new object, using an existing object as the prototype of the newly created object, just as seen in the prototype example above.
Another simple example:
Class is not an object — it is the blueprint of an object i.e. a template for creating objects. Classes are special functions. Classes are declared with the keyword class.
Class syntax is a nice and simpler way to use object-oriented programming and managing prototypes. They were introduced in ES6.
To add method to the class, we can simply it in the class curly braces without typing ‘Book.prototype.getAge’ i.e.:
We also have what is called static methods. Static methods is where we can actually have a method in class that we can use without instantiating an object.
Let’s say we want to have a subclass called ‘Magazine’ to have everything a book has but also has a month. It would be written as:
N.B: In order to call the parent constructor, we used the function called super.