Introduction
Most developers are familiar with object-oriented programming and design in languages like Java, C++ and C#. JavaScript, however, does not provide any obvious means to support this kind of object-oriented development. The result is that structured code becomes very hard to write for developers new to the world of JavaScript.
If you have written a few programs in JavaScript and wondered if it's possible to add more structure to your programs using object-oriented strategies, this tip is for you. In this post, we will look at the use of a small JavaScript utility that allows us to structure our JavaScript programs in the form of "classes" and objects.
Background
Traditionally, object-oriented programming relies on creating classes and creating object instances from classes. This approach to OOP was pioneered by a language known as Simula and eventually became the basis of object-oriented programming in popular languages such as C++ and Java.
Object-oriented programming in JavaScript, however, comes from a different OOP paradigm known as prototype-based programming. It was first introduced by the language Self with the aim of solving some problems in class-based programming. This style of programming has no concept of classes, and being very different from the class-based style we're usually familiar with, it requires a learning curve.
The utility presented below, however, provides a way to mimic class-based OOP in JavaScript.
Creating Objects
First, let's look at the basic structure for putting together a class:
var ClassName = Object.$extend({
initialize: function () {
this.publicMember = 'Some value';
this._privateMember = 'Another value';
},
publicFunction: function () {
},
_privateFunction: function () {
}
});
var anObject = new ClassName();
anObject.publicFunction();
New "classes" are created by extending the base Object
type. $extend
is a function that we have created for this purpose. initialize
is, by convention, called automatically every time we create a new object and is therefore the constructor. All private
and public
members should be declared in the initialize
function.
It is important to note that the "private
" members shown above are not really private at all. Unfortunately, JavaScript doesn't offer a means to easily mark members as private and for that reason we prefix them with an underscore to indicate them as such. anObject._privateFunction()
would have worked without any issues, but users of our class should be aware of our convention and not attempt to use it directly as it is prefixed with an underscore.
A Detailed Example
The following is an example of an "Animal
" class built using our utility. We will use this class for our examples on inheritance:
var Animal = Object.$extend({
initialize: function (gender) {
this._gender = gender;
this._foods = [];
},
getGender: function () { return this._gender; },
setGender: function (gender) { this._gender = gender; },
addFood: function (food) {
this._foods.push(food);
},
removeFood: function (food) {
for (var i = this._foods.length; i--;) {
if (this._foods[i] === food) {
this._foods.splice(i, 1);
break;
}
}
},
willEat: function (food) {
for (var i = this._foods.length; i--;) {
if (this._foods[i] === food)
return true;
}
return false;
}
});
There we have it! A class for creating Animal
objects. The following code sample creates Animal
objects and shows how they are used:
var lion = new Animal('male');
var parrot = new Animal('female');
lion.addFood('meat');
parrot.addFood('fruits');
lion.willEat('fruits');
lion.willEat('meat');
parrot.willEat('fruits');
lion._gender
Inheritance
Just like we created our base Animal
class by extending the type Object
, we can create child-classes of the Animal
class by extending it. The following snippet creates a "Human
" type that inherits from Animal
.
var Human = Animal.$extend({
initialize: function (name, gender) {
this.uber('initialize', gender);
this._name = name;
this.addFood('meat');
this.addFood('vegetables');
this.addFood('fruits');
},
goVegan: function () {
this.removeFood('meat');
},
nameWithTitle: function () {
return this._getTitlePrefix() + this._name;
},
_getTitlePrefix: function () {
if (this.getGender() === 'male') return 'Mr. ';
else return 'Ms. ';
}
});
The new Human
class can be used as follows:
var jack = new Human('Jack', 'male');
var jill = new Human('Jill', 'female');
jill.goVegan();
jill.nameWithTitle() + ' eats meat? ' + jill.willEat('meat');
jack.nameWithTitle() + ' eats meat? ' + jack.willEat('meat');
Notice the use of the "uber
" function in the constructor. Similar to "base
" and "super
" in C# and Java, it can be used to call the base class's functions. The next example will show another use of the uber
function.
It is important to note that the base class's constructor is automatically called without any arguments (new Animal()
) while defining the Human
subtype. We called it the second time using "uber
" to make sure it initializes the properties to proper values. It is important to make sure that the initialize function doesn't throw any error if called without any arguments.
More Inheritance Examples
The following code shows more examples of using OOP and inheritance using our handy utility:
var Cat = Animal.$extend({
initialize: function (gender) {
this.uber('initialize', gender);
this.addFood('meat');
},
speak: function () {
return 'purrr';
}
});
var DomesticCat = Cat.$extend({
initialize: function (gender) {
this.uber('initialize', gender);
this.addFood('orijen');
this.addFood('whiskas');
},
speak: function () {
return this.uber('speak') + ', meow!';
}
});
var WildCat = Cat.$extend({
initialize: function (gender) {
this.uber('initialize', gender);
},
speak: function () {
return this.uber('speak') + ', growl, snarl!';
}
});
var kitty = new DomesticCat('female');
var tiger = new WildCat('male');
'Domestic cat eats orijen? ' + kitty.willEat('orijen');
'What does the domestic cat say? ' + kitty.speak();
'What does the wild cat say? ' + tiger.speak();
Usage
To use this library, download the code and include inherit-min.js or inherit.js in your code.
History
A copy of the code is also available on GitHub under the BSD license: OOP in JavaScript: Inherit-js on GitHub.