Quick Index
Overview


This page walks through how to code a class in JavaScript.

The walk through is detailed and extensive, but the "Complete Source Code" at the bottom of this page is rather concise.

Object Diagram (Starting Point)


Firstly, we get familiar with our subject model.

A rectangle has a width and height.

We will code these as components (ivars) of the rectangle.
Object diagram of a rectangle we'll use to begin coding.
Rectangle
	width ivars
	height


Coding


We will now step through coding the class (with object diagram in hand).

Note that we will use the keyword this frequently in our code, which means this object.

Constructor (Object Structure)


The constructor is typically where we will setup the object structure (initialize the ivars from our object diagram).

Here we initialize the object's structure (a rectangle's ivars).
Remember js ivars are implicit ivars.
constructor(aWidth, aHeight) {
	//Initialize object structure
	this.width = aWidth;
	this.height = aHeight;
}

Getters


Getters simply return the object's ivars. They provide a way to get ivar values.
These are standard (common) methods.

This getter method simply gets and returns the ivar "width"
getWidth() {
	//Getter to get and return ivar "width"
	return this.width;
}
This getter method simply gets and returns the ivar "height"
getHeight() {
	//Getter to get and return ivar "height"
	return this.height;
}

Setters


Setters simply assign values to the object's ivars. They provide a way to set ivar values.

This setter method simply sets the ivar "width"
setWidth(value) {
	//Getter to assign passed param "value" to ivar "width"
	this.width = value;
}
This setter method simply sets the ivar "height"
setHeight(value) {
	//Getter to assign passed param "value" to ivar "height"
	this.height = value;
}

Instance Methods


The instance methods give the object its personality (define what it can do).

Compute area of rectangle as width * height
getArea() {
	//Compute and return area
	return this.width * this.height;
}
Compute perimeter (boundary length) of rectangle as total (sum) length of all edges.
getPerimeter() {
	//Compute and return perimeter
	return 2 * (this.width + this.height);
}
Compute rectangle diagonal which is the square root of the (w*w + h*h) where w and h are width and height, respectively. We tap into the js math library for sqrt (see "References" below)

getDiagonal() {
	//Compute and return diagonal
	const
		w = this.width,
		h = this.height;
	return Math.sqrt(w*w + h*h);
}
A little logic here to return a string indicating the type of rectangle we have.
One "if statement", and then the handy ternary operator

getShapeType() {
	//Return "square, wide rectangle, or narrow rectangle" as appropriate
	const
		w = this.width,
		h = this.height;
	if (w === h) {
		return "square";
	}
	return (w > h) ? "wide rectangle" : "narrow rectangle";
}
Flip width and height
flip() {
	//Flip width and height
	const w = this.width;
	this.width = this.height;
	this.height = w;
}
Increase each dimension by multiplying by the passed param "factor".
multiply(factor) {
	//Increase dimensions by multiplying them by passed param
	this.width = this.width * factor;
	this.height = this.height * factor;
}

Common


These methods are commonly used on objects (e.g. code on all our classes). Helpful for debugging, etc.

Return friendly representational display string (coder's choice). In this example, we return: "Rectangle: width=10 by height=5"

Hint: Coding "toString" is optional, but it is a good idea to code it for all of our classes (helpful for debugging).

toString() {
	//Friendly display string
	return `width=${this.width} by height=${this.height}`;
}

Try It Out


For simple classes, we can do a little lab play in the same file the class lives in.

This is "loose code" towards the bottom of our file (not in a class body).

The output here is:
Rectangle: width=10 by height=5
Rectangle Area: 50
Rectangle Shape Type: wide rectangle


//object play
function prn(o) { console.log(o); }

let rec = new Rectangle(10, 5);
prn("\nRectangle: " + rec.toString());
prn("Rectangle Area: " + rec.getArea());
prn("Rectangle Perimeter: " + rec.getPerimeter());
prn("Rectangle Diagonal: " + rec.getDiagonal());
prn("Rectangle Shape Type: " + rec.getShapeType());

rec = new Rectangle(1000, 1000);
prn("\nRectangle: " + rec.toString());
prn("Rectangle Area: " + rec.getArea());
prn("Rectangle Perimeter: " + rec.getPerimeter());
prn("Rectangle Diagonal: " + rec.getDiagonal());
prn("Rectangle Shape Type: " + rec.getShapeType());

Complete Source Code


/*
	Rectangle.js
	See associated document ("407 - Classes" - How to Code a Class)
	for detailed explanation of this class.
*/

class Rectangle {
	/*ivars (listed here for info only):
	width
	height*/
	
	//------------------------------------------------
	
		constructor(aWidth, aHeight) {
		//Initialize object structure
		this.width = aWidth;
		this.height = aHeight;
	}
	
	//------------------------------------------------
	//Getters (Basic)
	
	getWidth() {
		//Getter to get and return ivar "width"
		return this.width;
	}
	
	getHeight() {
		//Getter to get and return ivar "height"
		return this.height;
	}
	
	//------------------------------------------------
	//Setters
	
	setWidth(value) {
		//Getter to assign passed param "value" to ivar "width"
		this.width = value;
	}
	
	setHeight(value) {
		//Getter to assign passed param "value" to ivar "height"
		this.height = value;
	}
	
	//------------------------------------------------
	//Calcs
	
	getArea() {
		//Compute and return area
		return this.width * this.height;
	}
	
	getPerimeter() {
		//Compute and return perimeter
		return 2 * (this.width + this.height);
	}
	
	getDiagonal() {
		//Compute and return diagonal
		const
			w = this.width,
			h = this.height;
		return Math.sqrt(w*w + h*h);
	}
	
	getShapeType() {
		//Return "square, wide rectangle, or narrow rectangle" as appropriate
		const
			w = this.width,
			h = this.height;
		if (w === h) {
			return "square";
		}
		return (w > h) ? "wide rectangle" : "narrow rectangle";
	}
	
	//------------------------------------------------
	//Actions
	
	flip() {
		//Flip width and height
		const w = this.width;
		this.width = this.height;
		this.height = w;
	}
	
	multiply(factor) {
		//Increase dimensions by multiplying them by passed param
		this.width = this.width * factor;
		this.height = this.height * factor;
	}
	
	//------------------------------------------------
	//Common
	
	toString() {
		//Friendly display string
		return `width=${this.width} by height=${this.height}`;
	}

}

//object play
function prn(o) { console.log(o); }

let rec = new Rectangle(10, 5);
prn("\nRectangle: " + rec.toString());
prn("Rectangle Area: " + rec.getArea());
prn("Rectangle Perimeter: " + rec.getPerimeter());
prn("Rectangle Diagonal: " + rec.getDiagonal());
prn("Rectangle Shape Type: " + rec.getShapeType());

rec = new Rectangle(1000, 1000);
prn("\nRectangle: " + rec.toString());
prn("Rectangle Area: " + rec.getArea());
prn("Rectangle Perimeter: " + rec.getPerimeter());
prn("Rectangle Diagonal: " + rec.getDiagonal());
prn("Rectangle Shape Type: " + rec.getShapeType());