Skip to main content Accessibility Feedback

Constructor Pattern

Change MyLibrary to whatever namespace you’d like to use for your library. Constructors start with a capital letter.

Source Code

Examples

// Create new instances of the constructor
let dugg = new MyLibrary();
let kevin = new MyLibrary(4);

// Run methods
dugg.add(2);
kevin.subtract(1);
let total = dugg.total;

The Boilerplate

/**
 * Constructor Pattern Boilerplate
 */
let MyLibrary = (function () {

	/**
	 * Create the Constructor object
	 * @param {Number} start The starting amount
	 */
	function Constructor (start = 0) {
		this.total = start;
	}

	/**
	 * Add money to the total
	 */
	Constructor.prototype.add = function (num = 1) {
		this.total = this.total + num;
	};

	/**
	 * Remove money from the total
	 */
	Constructor.prototype.subtract = function (num = 1) {
		this.total = this.total - num;
	};

	return Constructor;

})();

Find this useful? You can support my work by purchasing an annual membership.