Overview - Javascript function acts as a class

This code snippets explained, How the function will act as a class in javascript. We can also define our own custom events for particular object through this class. Classes are very useful for storing many values into one object rather than creating many variables. A class holds many variables, methods, events. So using classes we can handle all the critical solution easily. Here I explained the class using one clear example.

For creating a new class in javascript there is no "class" keyword as like in "C#". In javascript class is define as like a function. See the below code,

function ClsStudent() {
this.Name = "";
this.Age = "";
this.Department = "";

this.AddStudent = function(tName, tAge, tDepartment) {
this.Name = tName;
this.Age = tAge;
this.Department = tDepartment;

this.click = function() {
alert("I am "+this.Name);

In the above code, I created a function named "ClsStudent". This function will act as a class. Within this class I created a three variables called Name, age and department. Also created one method named "AddStudent" with three parameters and one click event for this class.

The "AddStudent" method performs assigning a values to the class variables and the "Click" events fire whenever the click event is called as like function.

You can initialize an object for the "ClsStudent" class as like this,

var singleStudent = new ClsStudent();

Here, "singleStudent" is an instance of the "ClsStudent". Using this object you can access all the methods and variables of the "ClsStudent".
See the below code for adding some students information's into "ClsStudent" with the help of one array object.

var Students = new Array();
function ShowValues() {
var singleStudent = new ClsStudent();
singleStudent.AddStudent("damu", 12, "MCA");
Students[Students.length] = singleStudent;

singleStudent = new ClsStudent();
singleStudent.AddStudent("gopal", 20, "MCA");
Students[Students.length] = singleStudent;

singleStudent = new ClsStudent();
singleStudent.AddStudent("ubi", 120, "MCA");
Students[Students.length] = singleStudent;

for (var tIndex = 0; tIndex < Students.length; tIndex++) {

In the above "ShowValues" function just add three student records and displaying an alert message while the "Click" function is called. Here "Click" is a function not an event.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: