JavaScript Class Example – Modular Programming Technique

There are several ways to structure our JavaScript codes. Modular programming is a best practice for easy maintenance. Let us assume we have a class drawDiagram. In this class I have to implement many functionalities like draw a shape, drag n drop or create a flowchart. While drawing several shapes they have their own properties. To store all their property related programs here I created a separate js file with the name shproperty.js. In this file I created a class shProperty. Passing shape as a parameter. Depending upon the shape (rectangle, ellipse or circle) I can access the shape properties in my class.

As shProperty is a function it returns “exports”. Exports is an array. It holds properties & methods those need to access from an another class. Simply declaring a function propertyCalculation() is only accessible to the internals of the class. To create an external function like getProperty() & setProperty() you have to add this function to exports array.

Function init() is the part where you can initialize your class requirements. Before return the exports array call init() for execution. Refer to Object Oriented Programming (OOP) while declaring a private variable use _ before the variable name. For an example in below sample code I created a private variable _shape. In case it required to access _shape from out-side the class. Use get & set methods.

JavaScript Class Example

var shProperty = function (shape) {

var exports = {};
/* Variables in Global Scope */
var _shape = null;

/* Initialization */
function init() {
}

/* Internal Function */
function propertyCalculation() {
}

/* External Function */
exports.setProperty = function () {
};
exports.getProperty = function () {
};
_shape = shape;

init();
return exports;
};