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-
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 :-
now I am adding a “getFullName”method to the “person” object as below:-
now our “person” object is ready and I am creating a new person object using JavaScript new keyword as below.
now I am assigning firstName and lastName of this person p as below.
now I am accessing and printing the person full Name to the JavaScript debugger console as below.
The complete code is as below.

function person () {
    // body...
person.prototype.getFullName=function  () {    
    return this.firstName+ " "+ this.lastName;
var p=new person();

.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.


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 🙂


Leave a Reply

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

You are commenting using your 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