Blog

Example of Constructors In JavaScript

Sep 03, 2012 Blogs | JavaScript
In this example, we will discuss about that how we use constructors in our program in javascript.

Here we take an example in which when we click on the button the addition will be perform. For this follow these steps:

Step1: First we carate a button control like this, here we call a functiohich we will be discuss later:

<input id="btnAddition"  type="button"
value="Add" onclick="Add()" />
Step2: Now we write the function in javascript:

var values = function (a, b) { 
 this.a = a;
 this.b =b;
 };

Step3: After that we will create a function in which we create an object of type values like this:

function Add() { 
  var addition = new values(2,3); 
  alert(addition.a+addition.b); 
  }

Here we create an object and return the addition of the two numbers. This function is call on the onclick event of the button so when we click on the button an alert box will be appear like this:


1.png

Mahak Gupta

My name is Mahak Gupta. I am a C# Corner MVP.

  • 52rank
  • 1M readers
  • 2times
COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs