Constructors in JavaScript

In this post we will learn to create a JavaScript type using a constructor. Let us suppose we was to create a type called Product. We can create that as following,

 var Product = function (name, price) {
 this.Name = name;
 this.Price = price;

Above we have created a type called Product. Now we can create an object of type Product as following. You can access a particular property on the object of the type.

function createObject() {
 var myObject = new Product("pen",200);
 alert(myObject.Name + myObject.Price);

In this way you can create a type using constructor in JavaScript. Call createObject() function to display values of price and name of a product. You can do that as following


<input id="btnCreateObject"
 onclick="createObject()" />

I hope you find this post useful. Thanks for reading!

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 )

Google+ photo

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

Connecting to %s