Archive for the 'Object Oriented' Category

20
Apr

Creating & Using Classes in Javascript

Well, many of us know that javascript is an object-oriented language, but actually using it can be quite tricky. What was interesting was the way you define classes in JS. For example if we want to define a class called “student” with name, id and major as variables, and getName(), getId(), and getMajor() as methods of the student object, this is what we need to do:


//contructor for our student class
function Student(name, id, major)
{
this.name = name;
this.id = id;
this.major = major;
}
//methods for our Student class
Student.prototype.getName = function()
{
return this.name;
}
Student.prototype.getId = function()
{
return this.id;
}
Student.prototype.getMajor = function()
{
return this.major;
}

Now, if we want to use our javascript Student class, this is what we do:


var newStudent = new Student(”Ahsan”, “003052040″, “Computer Science”);
alert(newStudent.getName()+ ” ” + newStudent.getId() + ” ” + newStudent.getMajor());

This should print the student information.