Beauty of Prototype in JavaScript

Beauty of Prototype in JavaScript:

JavaScript is true object oriented language. JavaScript object is collection of name and values which are known as properties of an object. In JavaScript object we can add property or method at runtime which are not possible in case of class based object oriented language.

All JavaScript object are inherited from PROTOTYPE native object and have prototype property which is reference to internal prototype object. It means whenever we add property to a JavaScript object it gives reference to internal prototype object.

Let’s have an example to know about prototype.

STEP: 1
There are many ways to create an object in JavaScript one of them is:

//Empty funtion hence there is no property
//in javascript function can act as class

var company =function()
{
// You may add properties here
};

STEP: 2

Create two JavaScript functions “addCompanyName” and “getCompanyName” as given below:

function addCompanyName()
{
var objcompany = new company();//create object of company
objcompany.constructor.prototype.CompanyName = “MyCompany”;//add CompanyName property
}

function getCompanyName()
{
var objcompany = new company();
alert(objcompany.CompanyName);
}

STEP: 3

You are just close to test your example.

Create html page and put above JavaScript function in JavaScript section and add anchars with href (Add MyCompany  Company Name
Get Company Name).

Testing Steps:
1. Browse html page
2. Click on “Add MyCompany Company Name”
3. Click on “Get Company Name”, you will get MyCompany alert message.

This is my first blog if you find any mistake please revert back.

Thanks for Reading
Rukhsar Ahmad

Tagged:

One thought on “Beauty of Prototype in JavaScript

  1. Mazher Hassan August 26, 2009 at 11:02 am Reply

    Thanks for sharing valuable AJAX feature.

Leave a comment