Javascript : Object, Function, Prototype

Object

As we know an object is something that exists and owns a set of properties. The term object is used to refer anything in Javascript. From the list of objects available in Javascript, let us examine a few.

 typeof(Array); // function  
 typeof(Number); // function  
 typeof(String); // function  
 typeof(Math); // object  
 typeof(JSON); // object  

type function

  • Array
  • Number
  • String

type object

  • Math
  • JSON

The difference between these two group is that objects in the first group can be instantiated using new keyword, but the objects in the second group cannot be. So clearly behavior is what decides the type of an object in Javascript. To define behavior Javascript uses prototype, or a prototype defines the behavior of an object.

Prototype

object.__proto__ points to the prototype used by the object. Let us do a test in the console to explore an object

 var book = new Object();
book.proto




Here prototype of book is Object. To be more specific book.__proto__ points to Object.prototype

Or in another way, Object.prototype is the prototype Object offers to new objects.

 Object.prototype;
var book = new Object();
book.proto;


Object_proto_book2

What is important is that book is not cloning anything from Object, instead it re-using the behavior defined in Object.prototype by applying itself as the instance.

 var book = “book”
book.proto;


book_2

Here prototype of book is String. To be more specific book.__proto__ points to String.prototype, and you can see that book is inheriting the behavior of String via this link.

Function

Function in Javascript is a subroutine, which when called creates a closed scope. This closed scope is used create an object and store its properties.

Try the following console.

 Object.proto
Function.proro


object_proto2

 Object.proto.proto;
Function.
proro__.proto;


object_proto2

To make it more clear

obj_func_proto

So here

  • In the first level of the prototype chain Function is the prototype of both Object and Function
  • But in the second level it is Object

Please see the following diagram to understand how this has been achieved in multiple steps.


obj_func_proto


Function and Object are two building blocks of Javascript and features of these are efficiently utilized by recursively introducing them in the prototype chain in multiple steps.

Share