User Id :    Password :      New Member   Forgot Password  
How to define Classes in JavaScript
Description In this article we will see different ways of defining and instantiating an object.   No. of Views     2003
  Rating     0
Author Sumit Gupta   Posted On     19 Jul 2012
Tags Java Script    

Sample Code   Download Code

First important thing is that there are no classes in JavaScript. Functions can be used to simulate classes. In JavaScript, everything is an object and for inheritance, objects inherit from objects.


1. Using a function

This is the most common ways. We define a normal JavaScript function and then create an object by using the new keyword. We can use ‘this’ keyword to define properties and methods for an object.

For example:


function Car(brand) {
    this.brand = brand;
    this.color = "red";
    this.showInfo = showCarInfo;

function showCarInfo() {
    return this.brand + ' ' + this.color;



Now to use it, we can create an object of Car and call showCarInfo function. Like below:



var car = new Car('Audi');



We can also sets its property like below:



car.color = ‘black’;



Define methods internally

In above example, we see that the method showInfo() of the Car class was defined in a separate function showCarInfo(). This works fine but it has one disadvantage – we may end up defining a lot of functions and all are in the global namespace. This means we may have naming conflicts if we decide to create another function with the same name.
To avoid this problem, we can define our methods within the constructor function, like this:



function Car(brand) {
    this.brand = brand;
    this.color = "red";
    this.showInfo = function() {
	return this.brand + ' ' + this.color;



Using this syntax changes nothing in the way we instantiate the object and use its properties and methods.


2. Using literals

Literals are shorter way to define objects in JavaScript. To create an empty object we can do this way:



var obj = {};



So we can skip the class-like stuff and create an instance immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:



var car = {
    brand: "Audi",
    color: "red",
    showInfo: function () {
        	return this.brand + ' ' + this.color;



In this case we don't need to create an instance of the class, it already exists. So we simply start using this instance.


car.color = "black";



Happy programming!!!

About Author

About Author I am Sumit Gupta working in 3 Pillar Global Pvt. Ltd as Module Lead. I have 7+ year of experience in .Net technologies. I love to explore new technologies and write technical article. Sumit Gupta
No Photo
Country India
Company 3 Pillar Global Pvt. Ltd.
Home Page

Rate this article

Rating options from poor, fair, good, very good to excelent.  


Write your comment here.
Verification Code