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 Object, 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 into traditional way of defining Object and simulate them as classes.
As seen in the above example it is much simpler to define and reuse object in ES6. Hence, we would be using ES6 in all our examples.
3. Encapsulation – The process of wrapping property and function within a single unit is known as encapsulation.
Let’s understand encapsulation with an example.
In the above example we simply create an person Object using the constructor and Initialize it property and use it functions we are not bother about the implementation details. We are working with an Objects 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 undefine while their is a method which we can access from the person object(person1.getDetails_access()), by changing the way to define a function we can restrict its scope.
Lets’s understand inheritance with example:
In the above example, we define an Person Object with certain property and method and then we inherit the Person Object in the Student Object and use all the property and method of person Object as well define certain property and methods for Student.
Note: The Person and Student object both have same method i.e toString(), this is called as Method Overriding. Method Overriding allows method in a child class to have the same name and method signature as that of a parent class.
In the above code, super keyword is used to refer immediate parent class 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 firstname.lastname@example.org. 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.