Sunday, March 17, 2013

Difference Between Protoype and __proto__ in Javascript


So what’s the difference between __proto__ and prototype property in Javascript?


The prototype is used to create __proto__  Simple!

Yes, I know. That statement does not help much in terms of explaining what is going on :) But stick with me, the plan is to make it clear by the end of the post.

So let's dig into explaining this stuff!

The subject of prototype is related to Javascript objects and object creation and relation; so before going further, I recommend first reading Understanding Constructor Function and this Keyword in Javascript as this would provide some basic information that would help in understanding some of the basic concepts needed.


Saturday, March 16, 2013

Understanding Constructor Function and this Keyword in Javascript


Back in 2006 I wrote a post on using constructor functions in Javascript to create objects. This post builds on that post, expounding it a little bit further.

By definition, a constructor function is a normal Javascript function. Nothing more, nothing less. What makes a function a constructor is how it is used. When a function is used in such a way that it can create an object, by calling it with Javascript's new operator, then it becomes a constructor function.


This means all and any function you have in Javascript can be used as a constructor function.

var Person = function () {
  console.log("I am a function");
}
We can call this function normally:
Person(); //prints to the console "I am a function"
console.log(typeof Person) //prints to the console ‘function’
So let’s now use this function as a constructor and create an object:

var bond = new Person();
Now let us confirm that bond is indeed an object:

console.log(typeof bond) //this prints "Object"
Now that is all about Constructor functions.  It is as simple as that: A function that is the same as your normal Javascript function but can be used to create objects.

But you would notice that the object created above is empty (without properties) and maybe of little or no use. Compared to the example given in my previous post, which had properties. 

So how do you actually make an object with some already set properties at creation? Before we go ahead and look at this, its worth mentioning a characteristics of functions in Javascript (apart from this fact that they can be used to create objects).
Functions are first class citizens in Javascript and also Functions can have properties just as objects! Yes just like you add properties to an object, you can do same to a Javascript function.