Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

Creating a Class Definition In JavaScript

There are different ways to define classes in JavaScript. However, this is the most widely used and accepted at the moment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//class
function Person(sLastName, sFirstName, iAge) {
  this.lastName = sLastName;
  this.firstName = sFirstName;
  this.age = iAge;
  this.phoneNumbers = new Array();
}

//method
Person.prototype.showFullName = function() {
  alert(this.lastName + " " + this.firstName);
};

//instances
var oPerson1 = new Person("Lacava", "Alessandro", 30);
var oPerson2 = new Person("Brown", "John", 50);
oPerson1.phoneNumbers.push("1234567");
oPerson2.phoneNumbers.push("7654321");

oPerson1.showFullName(); //outputs Lacava Alessandro
alert(oPerson1.phoneNumbers); //outputs 1234567
oPerson2.showFullName(); //outputs Brown John
alert(oPerson2.phoneNumbers); //outputs 7654321

Comments