Saturday, December 7, 2013

More than just a function

When you start working with Javascript there is a good chance you will start using functions as building blocks of your program. Many programmers however do not realize that pretty much ordinary code as below creates two objects:

function Human() {
   // some code

function Dog() {
   // some code

Yes, you can call it as a function by Human() or Dog(), but you need to be aware that this is actually an object, with its properties, parent object and methods.

The objects above are Function objects. In addition to objects we just created there is already whole bunch of objects available in JS. Many of these e.g. Array, you are probably using everyday without much thinking. Function object is one of them.

As "inherit" is not really correct term for describing how JS organizes its objects into hierarchy, lets just say that Human and Dog functions objects above have internal property (link so to say) that reference a Function objects prototype property.

In ECMAScript documentation this internal property is referred to as [[Prototype]]. This property is not available in all browsers and it should not be used for anything more than debugging. In some implementations e.g. in Chrome if you should be able to access it via __proto__:


Every object in JS has this internal link. Function objects (such as Dog and Human we created and others e.g. Array) point to Function.prototype. Other objects will point to their respective prototypes e.g. when you create var cards=[] it will create Array object with cards.__proto__ referencing Array.prototype.

Its also worth noting that in modern browsers (and IE9+) you can access [[Prototype]] via Object.getPrototypeOf(instanceName) function. 

So you can imagine Function object as sitting above Human and Dog objects higher in hierarchy. So our hierarchy can be described as:


This Function.prototype property in turn via its [[Prototype]] property also has link to prototype higher in hierarchy. It is linked to Object.prototype property that sits on top of hierarchy. So to further describe relationship:


Now if we continue this trip and we as for Object.prototype.__proto__ we will get null as Object sits on top of hierarchy.

Ok, so we know what happens when we declare a function. We actually create Function object. We also learned that all objects have internal [[Prototype]] property. Unlike other objects however, function objects have two very important qualities:

1. can be used as constructors
2. its instances contain prototype property

These are important and very interesting topics and I will possibly cover these in future posts. I covered only tip of the iceberg here I hope that someone also found this useful however.

No comments:

Post a Comment