It is one of the few mainstream languages to have this kind of a method to inherit.
What is prototyping?
Prototyping means to copy the base for creation and then extend the base to the desired features. Then what is classical inheritance? It is to have a fixed frame for an object in the form of a class. This class is duplicated into an object form. For objects with more features, one must first extend the class and then create objects out of the extended class.
So to be clear
Classical Inheritance —> define classes and create an instance of these classes Prototypal Inheritance —> define objects and create new objects from old objects
In a classical language, it is very clear how code reuse happens. A class is used multiple times to create instances. By extending a class, we make sure the instances of the extended class have the properties of the parent class.
In a prototypal language, it is a bit hazy as to how the child object gets to use the properties defined in the parent. Usually, the language provides a construct/default property on the object to connect it to its parent. This is called delegation.
Object. This base object consists of some basic functions such as
prototype is given to each of the object(except the object literals). This provides the option to chain objects in a heirarchy.
Lets write some code to demonstrate this.
This is the basic working of the prototype object.
Lets look deeper.
This seems like correct behaviour. You dont want the child to be able to upset the parent.
This shows that the value in the object always overrides the value in the prototype object. Thus the priority of a variable decreases as we go up the prototype chain.
The idea of the prototype is that in the above example, all instances of
myChild reuse the prototype object
myObj. This means that new instance of
myObj is not created. All instances of
myChild will share one instance of
Creating a new Object from another Object.
The newer browsers allow us to use
Object.create(anotherObj) to create objects while inheriting from another object. For eg
What is the constructor?
Lets consider this -
- Change in prototype affects already created children.
- Children can always override parents properties.
- Set the constructor to know your roots!
blog comments powered by Disqus