Javascript Prototypal
Inheritance
--Manish Jangir--
What Is Inheritance?
In Object Oriented Programming, Inheritance means, code reusability and sharing.
Suppose you have a class that holds the common information about certain kind
of objects, then all the object classes can inherit those common methods and
properties from that parent class.
In general, all the popular languages have classical inheritance which means, we
have to create some classes that can be extended or consumed by their child
classes to inherit the parent properties.
But in Javascript, there is no concept of classes but we still need to make the
inheritance possible. This is the thing that can only be achieved by Prototypes.
Let’s Start Learning Prototype
Understand How A Construction Factory Works
As we know, we can create objects in javascript with below three methods:
1. var obj = new Object();
2. var obj = {} // This is object literal but just an alternate of first.
3. var obj = new AnyFunction();
In all of the above patterns, one thing is clear that the object is ultimately created
with a function constructor using new keyword. It means the very factory that
gives us objects as products is obviously a simple javascript function which we
use in our daily life coding. So it’s must here to learn and understand about this
factory’s behind the scene mechanism.
Construction Factory - Continue...
When you call a function with new keyword, the function creates an empty object
and assign it to a reserved keyword this and puts all the properties according to
the definition. At the end of function body, it returns that newly created object by
default.
A More Elaborated Example of Function Constructor
How Will You Achieve The Common Method?
One way to do that is, create a function in the constructor itself like below:
It looks like both of the objects are sharing
same method but that’s not true. If you see it
clearly, you will find that both of the objects
are having their own property/ method called
geNameWithCode.
If you modify this method of employee1, it
will not affect employee2 in either case.
Here Prototype Comes In The Picture
Prototype Inheritance pattern in Javascript lets you inherit the properties and
methods from one object to another to another to another…….
Prototype is a very simple object that is shared by all the objects which inherit
from it. But it's not their personal property. They can only share it. If anyone of
them modifies this prototype object in any way, All the other objects will have to
pay for it.
Before moving forward to actual object prototypes, let’s dive a little deep into the
function constructor again.
Constructor Factory - Mechanics
Whenever you declare a function with function abc() , and it goes through the
compilation phase (Though javascript is an interpreter language, but it contains,
Just In Time compiler), the javascript engine immediately converts our function
declaration to a special type of object that is completely hidden from us.
Why I said special type here because as we know, we create objects using a
function constructor new Object() where Object itself is a function then how a
function can be object????
But our JS engine in the browser does a lot behind it. What it does is, it converts
the function into an object that contains a single property called prototype
whose value is again a simple object. DIGEST IT TILL NEXT SLIDE...
Construction Factory Mechanics - Continued….
the
In the above snippet, we can see that behind the scene, the function is
converted or I can say achieves a behaviour so that it can also be used as an
object. So Now we can have any other properties on this function. But
prototype property is already available for us.
Now Understand What Prototype Property Really Is?
First of all, I would like to let you know that if you want to use a function as simple
caller without putting any new keyword (means creating object), Then you don’t
even need to read its spelling. This word is only useful if we are creating object
from a constructor factory function.
Ok we are creating object! Then what it is???
I told in previous, the default value of FunctionName.prototype is an empty
object. So whatever properties you assign on this empty object, they will be
available on your newly created objects. All the newly created objects will have a
hidden property called __proto__ that will directly references to the object that
have been assigned to your FunctionName.prototype = ??
Modify Any Property
HENCE PROVED
In the last slide, you got to know that what value we have there on FunctionName.prototype it
will be reflected on the __proto__ property of newly created objects.
NOW AN INTERESTING THING COMES HERE. YOU DON’T NEED TO USE .__proto__ TO
ACCESS ANY PROTOTYPE PROPERTY.
By the above example, we can’t even tell that the domain and experience properties have been defined on
object itself or its prototype. Can you??
Very Very Important Example
How A Property Lookup Works In Javascript
In Objects, how the property lookup is done is, whenever you try to access a property/key of
any object, the javascript engine will look on the object itself first, that whether a property of
that name is defined or not. If it finds any, it will return. But in case the property is not being
found on the object itself, it will be looked into its prototype (FunctionName.prototype)
object. If the prototype object has the property, it will return the value.
What happens, if the engine even doesn’t find the requested property on prototype object
also???
We know that prototype object is also a simple plain object that had also been created in the
same way like others. It means, it also contains a __proto__ property, The engine will reach
there also to find the property, if it still doesn’t find there, it will look into __proto__ of the
same.
Which means, the property lookup is followed by looking at the PROTOTYPE CHAIN. For
Ex.
propName -> yourObject -> __proto__ -> __proto__ -> __proto__ -> __proto__ …...
But It Will Lead To Infinite Chain Lookup :( :(
You might have been thinking that as each and every object contains a __proto__
property, then where this prototype chain lookup process will be ended.
It will end at Object.prototype.__proto__ whose value is null.
NOW WHAT IS THIS?????????
See, every object is first derived from new Object() that means,
Object.prototype will be __proto__ of all the created object out of this process. In
the previous examples, what we were doing is, just modify the __proto__.
WE WILL DISCUSS THIS IN MORE DETAILS LATER.
What About Setting A Prototype Property Without __proto__
So you are thinking to setup a prototype property without __proto__? Well you
can’t. The browser engine can’t read our brain that where we want to assign the
property exactly. So what it will do is just sets a new property on object itself. E.g.
Setting Props Without __proto__ Will Be Personal
Setting any property without __proto__ will be the personal property of that object
(Even if there is any on the prototype with same name, it will be overridden). So
whenever you get the property of the object, the JS engine will not reach on its
prototype if it finds any overriding property.
Setting Props Without __proto__ Will Be Personal
Setting any property without __proto__ will be the personal property of that object
(Even if there is any on the prototype with same name, it will be overridden). So
whenever you get the property of the object, the JS engine will not reach on its
prototype if it finds any overriding property.
Let’s Take A Real Life Example Of Prototypes
Function Employee(nm) {
This.name = nm;
} Employee.prototype
{
setCode: function () { },
getName: function () { },
getCode: function () { },
}
var m;
m = new Employee(“Manish”);
m.getName() // Manish
m.setCode(“EMP1212”)
m.getCode() // EMP1212
var m;
m = new Employee(“Viral
m.getName() // Viral
m.setCode(“5262”)
m.getCode() // 5262
var m;
m = new Employee(“Rahul”);
m.getName() // Rahul
m.setCode(“1220”)
m.getCode() // 1220
Link Between Function And It’s Prototype Object
As we saw that each function has a prototype property and its value is a simple
object. But how the prototype object is has a relation with the function? Well the
prototype object also has a property called constructor which directly points to
the main function So that we can know in future, which constructor the prototype is
of.
Sounds Confusing???
Look at the next slides!!!
Link Between Function And It’s Prototype Object
In the left example, the prototype object of
any function has a constructor property which
directly references to the main Constructor
Function. So every function prototype object
and their constructed object’s __proto__, both
will have the same constructor property.
Remember The object properties are used by
references.
The Object Function
In this slide, we will talk about Object function. It may be a confusing name you
must have to understand it. Is it an object or a function?? Well it is both. In
javascript client (Browser or Node), as we have a global object window. Similarly,
we have some global functions as well. Ojbect is one of them. Something like
function Objec(){}.
We have already seen several times that, the empty object are created with the
syntax:
var obj = new Object();
Doesn’t it look like all the previous constructor function examples we saw?
The Object Function Contd….
Well each and every object in javascript is natively inherited from the constructor
function Object. Forget all your custom function for a while. Look at the following
code carefully.
Constructor Static Methods Prototype Methods
The Object Function Contd….
As we saw in the last slide, whenever you create a new object using new
Object(), the newly created object has a __proto__ property that references to
Object.prototype. It defines the native methods that are useful in Object
operations.
Object
(constructor)
Object.prototype
Employee
(constructor)
Employee.prototype
PHPEmployee
(constructor)
PHPEmployee.prototype
var emp = new
PHPEmployee();
prototype
prototype
prototype
constructor
constructor
constructor
__proto__
__proto__
__proto__
null
__proto__
Object.create Utility Method (Returns New Object)
We have known that we can get the benefits of prototype chain as it can go as long as the
engine doesn’t find the value of last prototype as Object.prototype.
But to make this chain??
There is a static utility method defined on Object called Object.create that helps us to
create a new object which has certain prototype.
The first argument in the function is, the prototype object of newly created object and the
second is the definition of our new object. If we don’t pass the second param, then it will
create an empty object with prototype we passed in first param. Remember, each object
has prototype as Object.prototype if it was not overridden by Object.create.
Syntax: Object.create(prototype_of_new_object, {newObjectDefinition})
Without Constructor With Constructor
Object.create Example
Look, How the native Array is
implemented in the javascript
runtime.
Makes Sense????
Look, How the native
Number Constructor is
implemented in the
javascript runtime.
Thank You!

Javascript Prototypal Inheritance - Big Picture

  • 1.
  • 2.
    What Is Inheritance? InObject Oriented Programming, Inheritance means, code reusability and sharing. Suppose you have a class that holds the common information about certain kind of objects, then all the object classes can inherit those common methods and properties from that parent class. In general, all the popular languages have classical inheritance which means, we have to create some classes that can be extended or consumed by their child classes to inherit the parent properties. But in Javascript, there is no concept of classes but we still need to make the inheritance possible. This is the thing that can only be achieved by Prototypes.
  • 3.
  • 4.
    Understand How AConstruction Factory Works As we know, we can create objects in javascript with below three methods: 1. var obj = new Object(); 2. var obj = {} // This is object literal but just an alternate of first. 3. var obj = new AnyFunction(); In all of the above patterns, one thing is clear that the object is ultimately created with a function constructor using new keyword. It means the very factory that gives us objects as products is obviously a simple javascript function which we use in our daily life coding. So it’s must here to learn and understand about this factory’s behind the scene mechanism.
  • 5.
    Construction Factory -Continue... When you call a function with new keyword, the function creates an empty object and assign it to a reserved keyword this and puts all the properties according to the definition. At the end of function body, it returns that newly created object by default.
  • 6.
    A More ElaboratedExample of Function Constructor
  • 7.
    How Will YouAchieve The Common Method? One way to do that is, create a function in the constructor itself like below: It looks like both of the objects are sharing same method but that’s not true. If you see it clearly, you will find that both of the objects are having their own property/ method called geNameWithCode. If you modify this method of employee1, it will not affect employee2 in either case.
  • 8.
    Here Prototype ComesIn The Picture Prototype Inheritance pattern in Javascript lets you inherit the properties and methods from one object to another to another to another……. Prototype is a very simple object that is shared by all the objects which inherit from it. But it's not their personal property. They can only share it. If anyone of them modifies this prototype object in any way, All the other objects will have to pay for it. Before moving forward to actual object prototypes, let’s dive a little deep into the function constructor again.
  • 9.
    Constructor Factory -Mechanics Whenever you declare a function with function abc() , and it goes through the compilation phase (Though javascript is an interpreter language, but it contains, Just In Time compiler), the javascript engine immediately converts our function declaration to a special type of object that is completely hidden from us. Why I said special type here because as we know, we create objects using a function constructor new Object() where Object itself is a function then how a function can be object???? But our JS engine in the browser does a lot behind it. What it does is, it converts the function into an object that contains a single property called prototype whose value is again a simple object. DIGEST IT TILL NEXT SLIDE...
  • 10.
    Construction Factory Mechanics- Continued…. the In the above snippet, we can see that behind the scene, the function is converted or I can say achieves a behaviour so that it can also be used as an object. So Now we can have any other properties on this function. But prototype property is already available for us.
  • 11.
    Now Understand WhatPrototype Property Really Is? First of all, I would like to let you know that if you want to use a function as simple caller without putting any new keyword (means creating object), Then you don’t even need to read its spelling. This word is only useful if we are creating object from a constructor factory function. Ok we are creating object! Then what it is??? I told in previous, the default value of FunctionName.prototype is an empty object. So whatever properties you assign on this empty object, they will be available on your newly created objects. All the newly created objects will have a hidden property called __proto__ that will directly references to the object that have been assigned to your FunctionName.prototype = ??
  • 12.
  • 13.
    In the lastslide, you got to know that what value we have there on FunctionName.prototype it will be reflected on the __proto__ property of newly created objects. NOW AN INTERESTING THING COMES HERE. YOU DON’T NEED TO USE .__proto__ TO ACCESS ANY PROTOTYPE PROPERTY. By the above example, we can’t even tell that the domain and experience properties have been defined on object itself or its prototype. Can you??
  • 14.
  • 15.
    How A PropertyLookup Works In Javascript In Objects, how the property lookup is done is, whenever you try to access a property/key of any object, the javascript engine will look on the object itself first, that whether a property of that name is defined or not. If it finds any, it will return. But in case the property is not being found on the object itself, it will be looked into its prototype (FunctionName.prototype) object. If the prototype object has the property, it will return the value. What happens, if the engine even doesn’t find the requested property on prototype object also??? We know that prototype object is also a simple plain object that had also been created in the same way like others. It means, it also contains a __proto__ property, The engine will reach there also to find the property, if it still doesn’t find there, it will look into __proto__ of the same. Which means, the property lookup is followed by looking at the PROTOTYPE CHAIN. For Ex. propName -> yourObject -> __proto__ -> __proto__ -> __proto__ -> __proto__ …...
  • 16.
    But It WillLead To Infinite Chain Lookup :( :( You might have been thinking that as each and every object contains a __proto__ property, then where this prototype chain lookup process will be ended. It will end at Object.prototype.__proto__ whose value is null. NOW WHAT IS THIS????????? See, every object is first derived from new Object() that means, Object.prototype will be __proto__ of all the created object out of this process. In the previous examples, what we were doing is, just modify the __proto__. WE WILL DISCUSS THIS IN MORE DETAILS LATER.
  • 17.
    What About SettingA Prototype Property Without __proto__ So you are thinking to setup a prototype property without __proto__? Well you can’t. The browser engine can’t read our brain that where we want to assign the property exactly. So what it will do is just sets a new property on object itself. E.g.
  • 18.
    Setting Props Without__proto__ Will Be Personal Setting any property without __proto__ will be the personal property of that object (Even if there is any on the prototype with same name, it will be overridden). So whenever you get the property of the object, the JS engine will not reach on its prototype if it finds any overriding property.
  • 19.
    Setting Props Without__proto__ Will Be Personal Setting any property without __proto__ will be the personal property of that object (Even if there is any on the prototype with same name, it will be overridden). So whenever you get the property of the object, the JS engine will not reach on its prototype if it finds any overriding property.
  • 20.
    Let’s Take AReal Life Example Of Prototypes Function Employee(nm) { This.name = nm; } Employee.prototype { setCode: function () { }, getName: function () { }, getCode: function () { }, } var m; m = new Employee(“Manish”); m.getName() // Manish m.setCode(“EMP1212”) m.getCode() // EMP1212 var m; m = new Employee(“Viral m.getName() // Viral m.setCode(“5262”) m.getCode() // 5262 var m; m = new Employee(“Rahul”); m.getName() // Rahul m.setCode(“1220”) m.getCode() // 1220
  • 21.
    Link Between FunctionAnd It’s Prototype Object As we saw that each function has a prototype property and its value is a simple object. But how the prototype object is has a relation with the function? Well the prototype object also has a property called constructor which directly points to the main function So that we can know in future, which constructor the prototype is of. Sounds Confusing??? Look at the next slides!!!
  • 22.
    Link Between FunctionAnd It’s Prototype Object In the left example, the prototype object of any function has a constructor property which directly references to the main Constructor Function. So every function prototype object and their constructed object’s __proto__, both will have the same constructor property. Remember The object properties are used by references.
  • 23.
    The Object Function Inthis slide, we will talk about Object function. It may be a confusing name you must have to understand it. Is it an object or a function?? Well it is both. In javascript client (Browser or Node), as we have a global object window. Similarly, we have some global functions as well. Ojbect is one of them. Something like function Objec(){}. We have already seen several times that, the empty object are created with the syntax: var obj = new Object(); Doesn’t it look like all the previous constructor function examples we saw?
  • 24.
    The Object FunctionContd…. Well each and every object in javascript is natively inherited from the constructor function Object. Forget all your custom function for a while. Look at the following code carefully. Constructor Static Methods Prototype Methods
  • 25.
    The Object FunctionContd…. As we saw in the last slide, whenever you create a new object using new Object(), the newly created object has a __proto__ property that references to Object.prototype. It defines the native methods that are useful in Object operations.
  • 26.
    Object (constructor) Object.prototype Employee (constructor) Employee.prototype PHPEmployee (constructor) PHPEmployee.prototype var emp =new PHPEmployee(); prototype prototype prototype constructor constructor constructor __proto__ __proto__ __proto__ null __proto__
  • 27.
    Object.create Utility Method(Returns New Object) We have known that we can get the benefits of prototype chain as it can go as long as the engine doesn’t find the value of last prototype as Object.prototype. But to make this chain?? There is a static utility method defined on Object called Object.create that helps us to create a new object which has certain prototype. The first argument in the function is, the prototype object of newly created object and the second is the definition of our new object. If we don’t pass the second param, then it will create an empty object with prototype we passed in first param. Remember, each object has prototype as Object.prototype if it was not overridden by Object.create. Syntax: Object.create(prototype_of_new_object, {newObjectDefinition})
  • 28.
    Without Constructor WithConstructor Object.create Example
  • 29.
    Look, How thenative Array is implemented in the javascript runtime. Makes Sense????
  • 30.
    Look, How thenative Number Constructor is implemented in the javascript runtime.
  • 31.