dreamsys software

JavaScript Shell Scripting Tutorial

Enums

An Enum, or enumeration, is a list of constant values. Many programming languages have this concept, however JavaScript does not. The problem is that JavaScript is not a type-safe language. However you can create enums in JavaScript using other methods.

Let's say you have a User class and it has a property "gender", you want the user to specify one of three values: male, female or unspecified. We can make the gender property an enum.

#!/usr/bin/env node

var Gender = {
	MALE : 0,
	FEMALE : 1,
	UNSPECIFIED : 2
};

var User = function() {
	var self = this;

	self.name = '';
	self.age = 0;
	self.gender = Gender.UNSPECIFIED;

	self.display = function() {
		if (self.gender == Gender.MALE) {
			console.log(self.name + ' is male');
		} else if (self.gender == Gender.FEMALE) {
			console.log(self.name + ' is female');
		} else {
			console.log(self.name + ' did not specify a gender.');
		}
	}
};

var user1 = new User();
user1.name = 'Mike';
user1.gender = Gender.MALE;

var user2 = new User();
user2.name = 'Sally';
user2.gender = Gender.FEMALE;

var user3 = new User();
user3.name = 'Pat';

user1.display();
user2.display();
user3.display();

In the next section we will learn how to integrate with the shell.

Prev (Lists & Maps) | Next (Shell Integration)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6