There are certain features or mechanisms which makes a Language Object-Oriented like:
- Using an Object Literal
- Using an Object Constructor:
- Using Object.create() method: The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
2. Classes– Classes are blueprint of an Object. A class can have many Objects because class is a template while Object are instances of the class or the concrete implementation.
Note: Even the classes provided by ECMA2015 are objects.
–Mozilla Developer Network
Lets use ES6 classes then we will look at the traditional way of defining an Object and simulate them as classes.
As seen in the above example it is much simpler to define and reuse objects in ES6. Hence, we would be using ES6 in all of our examples.
3. Encapsulation – The process of wrapping properties and functions within a single unit is known as encapsulation.
Let’s understand encapsulation with an example.
In the above example we simply create a person Object using the constructor and Initialize its properties and use its functions. We are not bothered with the implementation details. We are working with an Object’s interface without considering the implementation details.
In the above example we try to access some property(person1.firstname) and functions(person1.getDetails_noaccess) but it returns undefined while their is a method which we can access from the person object(person1.getDetails_access()). By changing the way we define a function we can restrict its scope.
Let’s understand inheritance with an example:
In the above example, we define an Person Object with certain properties and methods and then we inherit the Person Object in the Student Object and use all the properties and methods of the person Object as well as define certain properties and methods for the Student Object.
Note: The Person and Student object both have same method (i.e toString()), this is called Method Overriding. Method Overriding allows a method in a child class to have the same name and method signature as that of a parent class.
In the above code, the super keyword is used to refer to the immediate parent class’s instance variable.
This article is contributed by Sumit Ghosh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.