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
- Phone Number
The Customer class also contains methods such as GetCustomer to get the customer information.
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());
In ECMAScript 6, we also have a new Class syntax:
class Customer { constructor (firstname, lastname, email, phonenumber) { this.firstname = firstname; this.lastname = lastname; this.email = email; this.phonenumber = phonenumber; } GetCustomer() { 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 console.log(Customer00001.firstname);
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL