Especially when JS-ninjas who are known for their contributions to the language itself, like Douglas Crockford say it, you might want to believe it.
So, what makes any programming language Object Oriented? Well, there are various definitions on this but essentially, for any language to be Object Oriented language it has to support following important features at the least:
1. Encapsulation - Object’s internal working is hidden from the rest of the application.
2. Inheritance - Object can inherit properties and method from a parent object.
3. Polymorphism - Object can having multiple forms.
Encapsulation simply means, private data of an Object should not be directly accessible to the outside world. There should be methods to get and to set the internal properties of that object.
First, let’s see, what is NOT encapsulation?
Although it is perfectly legal to write the above code, it is not a recommended way to write it that way due to various reasons like the security of the code, its lack of ability to validate the code, and much more.
So, what is encapsulation?
The above code is encapsulated because the property “fullName” cannot be accessed from anywhere outside the “Person” function.
This feature gives the ability to an object to inherit functionality and properties from parent objects.
In the above example, Object.create() is used to create a new object by specifying its prototype object. A “tiger” object was created using “animal” as its prototype. And due to prototypal inheritance, “tiger” object also got “sleeps” property from its parent “animal” object.
“animal” is a base object. Let’s inherit “lion” and “tiger” objects from “animal”.
We used Object.create() method to inherit “lion” and “tiger” objects from “animal”. Then for the “tiger” object we overrode the “getInfo” function to be more specific to that object. But, we did not do the same for the “lion” object.
Now, let’s see what happens when “getInfo” function is called on both the objects.
As we did not override “getInfo” function for “lion” object it uses the “getInfo” function of its parent, that is, “animal” object. On the other hand, we wrote a specific “getInfo” function for the “tiger” object hence when the “getInfo” was executed on it, it executed the specific function to that object instead of the “getInfo” function of its parent Animal object.
The “getInfo” function is resolved at runtime, and this is called late binding or dynamic Polymorphism.