Classes in JavaScript

Leave a comment

There are different ways to define classes in JavaScript. Let’s look at some examples.

Let’s say you want to define a class for a Customer. The customer contains attributes such as:

  • First Name
  • Last Name
  • Email
  • Phone Number

The Customer class also contains methods such as GetCustomer to get the customer information.

Create a new file with the extension .html, e.g. JSClasses.html. Add <script> tags. These will be our placeholders for our JavaScript code:

// JavaScript code to go here

Now, to create a customer class, we can do the following. Note we are creating a function to store our Customer class:

function Customer (firstname, lastname, email, phonenumber) {
    this.firstname = firstname;
    this.lastname = lastname; = email;
    this.phonenumber = phonenumber;
    this.GetCustomer = function() {
        return this.firstname + ' ' + this.lastname + ' ' + + ' ' + this.phonenumber;

// Create objects
var Customer00001 = new Customer("Bob", "Smith", "", "555-111-2222");
var Customer00002 = new Customer("James", "Johnson", "", "555-111-3333");

// Print out the first name of the Customer00001

This returns “Bob”.

If we add:


We get the following returned:

You can also create objects (and include functions) using the new Object():

var customerA = new Object(); = "Bob";
customerA.GetCustomer = function() {

This returns:

Object Literals

You can also create objects using name value pairs. E.g.

var Customer00003 = {firstname:"Robert", lastname:"Williams", email:"", phone:"555-111-3333"};

We can then access properties of our object, e.g.


Notice there is no GetCustomer in this example. We can add functions to the object by:

var Customer00004 = { 
	GetCustomer: function() {
        return this.firstname + ' ' + this.lastname + ' ' + + ' ' + this.phonenumber;



Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

five + ten =