Sunday, November 22, 2015

The Real JavaScript

Hi, In this article i am going to explain the internal architecture of the JavaScript object. After reading this article you have a clear understanding of JavaScript Object, what is __proto__ and prototype chaining in JavaScript.

lets start :)

There are three ways to create an object in JavaScript.

1. Using an object literal

var Person  = {};

2. Using the new keyword

var Person = new Object();

3. Inheriting Object.prototype

var Person = Object.create(Object.prototype);

All of these create same person object.
Here var Person = Object.create(Object.prototype); means that Person object extends from Object.prototype Object.

If you want to add some property to the Person object then this can be added as below.

Person.name = "deepak";

Now Person Object has one property name of type string and has value deepak in it.

So lets understand this simple object by structure.


In the above image you can see the structure of Person Object. Here Person Object extends from Object.prototype Object.

__proto__ provides link between the objects.

For a property it will look into the Object
if unable to find then it will look into the Object.__proto__
if unable to find it will look into the Object.__proto__.__proto__ and so on, until it find null, this is called prototype chaining in JavaScript.

Longer the prototype chain more the access time.

Here Person object accessing hasOwnProperty() method by prototype chaining.

No comments:

Post a Comment