5- Instanceof Operator:
As we all know, the instanceof operator returns true if an object is a instance of a class/ function (ES5) and vice versa. Lets have a look at below example:
How does the instanceof operator works internally?
The instanceof operator tries to compare the prototype chain of constructor of the class with the prototype of instance of the class and if they match, it returns true, else false. This thought leads us to a perspective, wherein, just matching the prototype of a class with instance of other class, corrupts this instanceof operator and kills it reliability as below:
In the above example, we have created a new class Bike and created an instance of it as myBike. In addition to the above, we have added the prototype of Bike to be prototype of Car. Since instance of checks only for the prototype chain, for mybike instance of Car (which is not true), it returns true.
Object.defineProperty(obj, prop, descriptor)
//obj - your target object where the property will be added
//prop - The name of the property to be added
//descriptor - Details about the property.
The descriptor is again an object with 4 properties.
configurable — Determines whether the property’s descriptor is editable and if the property is deletable. Defaults to false
enumerable — Determines whether the property is available to Object.assign, spread operator and also in for..in loop. Defaults to false
writable— Determines whether the value of the property can be changed. Defaults to false.
value — This descriptor stores the value of the property.
Have a look at the below example:
In the above example, we have made the property age as writable false and hence, even if we try to change the value of age, it doesn’t change. In the other example, we have made configurable false and the property is not deletable.
7 — OLOO
At times, we don’t really need to create a constructor using new keyword and involve in prototype for Inheritance. Instead we can readily use Object.create and incorporate inheritance using OLOO concept.
Lets look at below example:
In the above example we have still achieved inheritance but without prototype or constructor or new keyword. Hence OLOO way of inheritance comes handy for specific requirements.
Though Prototypal Inheritance is an ocean, I have tried to dive deep enough to cover up diverse topics. Any suggestions are highly appreciated.
Test what you have learned so far — here. Thanks for reading through pretty long article.