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:

<script> 
// JavaScript code to go here
</script>

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;
    this.email = email;
    this.phonenumber = phonenumber;
	
    this.GetCustomer = function() {
        return this.firstname + ' ' + this.lastname + ' ' + this.email + ' ' + this.phonenumber;
    };
}

// Create objects
var Customer00001 = new Customer("Bob", "Smith", "bsmith@test.com", "555-111-2222");
var Customer00002 = new Customer("James", "Johnson", "jjohnson@test.com", "555-111-3333");

// Print out the first name of the Customer00001
alert(Customer00001.firstname);

This returns “Bob”.

If we add:

alert(Customer00001.GetCustomer());

We get the following returned:

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

var customerA = new Object();
customerA.name = "Bob";
customerA.GetCustomer = function() {
 return this.name;
 };
alert(customerA.GetCustomer());

This returns:

Object Literals

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

var Customer00003 = {firstname:"Robert", lastname:"Williams", email:"jjohnson@test.com", phone:"555-111-3333"};

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

alert(Customer00003.firstname);

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

var Customer00004 = { 
	firstname:"Robert", 
	lastname:"Williams", 
	email:"rwilliams@test.com", 
	phonenumber:"555-111-5555",
	GetCustomer: function() {
        return this.firstname + ' ' + this.lastname + ' ' + this.email + ' ' + this.phonenumber;
    }
};

alert(Customer00004.GetCustomer());

 

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 =