PROWAREtech

articles » current » javascript » classes

JavaScript: Classes

Several ways to create classes.

Creating Classes with Functions

Newer versions of JavaScript support the class keyword, but first examine how to create one without this keyword using prototypes.

Functions are objects and each function is created with a prototype property. The benefit of using the prototype is that all of its properties and methods are shared among object instances. For example:

function Animal(type, age, name) { // this is the constructor
	this.type = type; // can use "this" keyword because the "new" keyword will be used
	this.age = age;
	this.name = name;
}
Animal.prototype.sayAnything = function (anything) { alert(this.name + " (a " + this.type + ", age " + this.age + ") says " + anything); }; // shared among all Animal instances

var dog = new Animal("dog", 5, "Spot"); // must use new keyword
dog.sayAnything("HELLO");

Example usage:

function Animal(type, age, name) { // this is the constructor
	this.type = type;
	this.age = age;
	this.name = name;
}
Animal.prototype.sayAnything = function (anything) { alert(this.name + " (a " + this.type + ", age " + this.age + ") says " + anything); }; // shared among all Animal instances

var dog = new Animal("dog", 5, "Spot"); // must use new keyword
dog.sayAnything("HELLO");
var cat = new Animal("cat", 9, "Whiskers"); // must use new keyword
cat.sayAnything("HELLO");
alert(dog.sayAnything == cat.sayAnything); // true
alert(dog.sayAnything === cat.sayAnything); // true

Creating Classes with the class Keyword

This only applies to EcmaScript 6 and newer versions of JavaScript.

With the class keyword, prototypes are essentially out the window. The following code basically duplicates what is above.

class Animal {
	constructor(type, age, name) { // shared among all Animal instances
		this.type = type;
		this.age = age;
		this.name = name;
	}
	sayHello() { alert(this.name + " says hello"); }; // shared among all Animal instances
}
var dog = new Animal("dog", 5, "Spot");
dog.sayHello();

Example usage (NOTE: does not run on Internet Explorer):

class Animal {
	constructor(type, age, name) {
		this.type = type;
		this.age = age;
		this.name = name;
	}
	sayHello() { alert(this.name + " says hello"); };
}

var dog = new Animal("dog", 5, "Spot");
dog.sayHello();
var cat = new Animal("cat", 9, "Whiskers");
cat.sayHello();
alert(dog.sayHello == cat.sayHello); // true
alert(dog.sayHello === cat.sayHello); // true

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT