Javascript OOP

Blog: Javascript

Another way to go about some OOP for JavaScript. The bracket incased function initialises a self executing anonymous function that encases the class. In the example below are several ways of calling the class methods and properties.

Main Application or JS file.

var person = new Human("male", "28", "New Zealand", "brown");
console.log(person.nationality);
console.log(person.walking_speed);
person.startWalking();

A JS Class Example

/**
 * Create a self executing anonymous function
 * Use the '()' brackets at the end to initalise this method.
 * Pass in variables when executing.
 */
(function(window) {
 
	// Public variables
	Human.prototype.walking_speed = 10;
 
	// Static variables
	Human.running_speed = 20;
 
	function Human(sex, age, nationality, eyeColor) {
		// public variables
		this.sex 			= sex;
		this.age 			= age;
		this.nationality 	= nationality;
 
		// private variables
		var _eyeColor = eyeColor;
 
		this.getEyeColor = function(){ return _eyeColor; };
	}
 
	Human.prototype.startWalking = function() {
		console.log(getDemographic(this) + " is walking");
	};
 
	// Private function
	function getDemographic(context) {
		return context.nationality + " " + context.sex + " " + context.getEyeColor();
	}
 
	window.Human = Human;
 
}(window));

If you want to create a singleton you can do it as follows.

/**
 * Create and instantiate a JS Singleton
 */
var Nationality = new function() {
    this.name = "New Zealand";
    this.location = "Australasia";
    this.getInfo = function () {
        return this.name + ' is located in ' + this.location;
    };
}
 
Nationality.name = "Australian";
alert(Nationality.getInfo());

No comments

Post a Reply