Example of Constructors In JavaScript

Introduction

 
Here we take an example in which when we click on the button the addition will be performed. For this follow these steps:
 
Step1: First we carate a button control like this, here we call a function which we will be discussed later:
  1. <input id="btnAddition"  type="button"  
  2. value="Add" onclick="Add()" />  
Step2: Now we write the function in javascript:
  1. var values = function (a, b) {   
  2.  this.a = a;  
  3.  this.b =b;  
  4.  };  
Step3: After that, we will create a function in which we create an object of type values like this:
  1. function Add() {   
  2.   var addition = new values(2,3);   
  3.   alert(addition.a+addition.b);   
  4.   }  
Here we create an object and return the addition of the two numbers. This function is called on the onclick event of the button so when we click on the button an alert box will appear like this:
 
1.png