JavaScript Objects using function prototype

Hi, In the below post we will explore how we can use function prototype property for object oriented programming in JavaScript. In JavaScript functions are objects and every function has prototype property as soon as they get created. we can use this property to add data as well as behaviors i.e. properties and methods to the function. To demonstrate this I have created a “person” function as below-
image 
now suppose I want to add some property to this function(or we can say person object). I am adding firstName,lastName and PhoneNo as below :-
image
now I am adding a “getFullName”method to the “person” object as below:-
image
now our “person” object is ready and I am creating a new person object using JavaScript new keyword as below.
image
now I am assigning firstName and lastName of this person p as below.
image
now I am accessing and printing the person full Name to the JavaScript debugger console as below.
image
The complete code is as below.

 
function person () {
    // body...
};
 
person.prototype.firstName="";
person.prototype.lastName="";
person.prototype.PhoneNo="";
 
 
person.prototype.getFullName=function  () {    
    return this.firstName+ " "+ this.lastName;
};
 
var p=new person();
 
p.firstName="Navin";
p.lastName="Prasad";
 
console.log(p.getFullName());

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

and below is debugger output.

image

In the above post we learned that how to use JavaScript prototype property to assign functions and properties to the JavaScript object.

Hope you find this post useful. Thanks for reading. Happy Coding 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s