Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Simple JavaScript OOP for C++, Java and C# Developers

2.67/5 (2 votes)
30 Dec 2014BSD3 min read 13.6K   214  
This tip provides an approach to object-oriented programming for developers familiar with class-based OOP in languages such as C++ and Java.

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:

JavaScript
var ClassName = Object.$extend({
    initialize: function () {
        //this is the mandatory constructor. All class members should be initialized here.
        this.publicMember = 'Some value';
        this._privateMember = 'Another value';
    },

    publicFunction: function () {
        //Code for a public function.
    },

    _privateFunction: function () {
        //Code for a private 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:

JavaScript
//This is a basic "Animal" class. $extend is a method
//provided by the utility. To build a new class, we
//"inherit" from the base Object type

var Animal = Object.$extend({

    //"initialize" is the constructor function for objects
    //of type Animal.

    initialize: function (gender) {
        //Notice that we declare members _gender and _food in
        //the constructor. Declaring member variables in the
        //constructor is important.

        this._gender = gender;
        this._foods = [];
    },

    //Simple getter and setter functions for the _gender
    //property

    getGender: function () { return this._gender; },
    setGender: function (gender) { this._gender = gender; },

    //This function adds an item to the _food array

    addFood: function (food) {
        this._foods.push(food);
    },

    //self-explanatory -- removes an item from the
    //_foods array

    removeFood: function (food) {
        for (var i = this._foods.length; i--;) {
            if (this._foods[i] === food) {
                this._foods.splice(i, 1);
                break;
            }
        }
    },

    //Boolean function to check if this animal will eat a particular type of food.

    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:

JavaScript
var lion = new Animal('male');
var parrot = new Animal('female');

lion.addFood('meat');
parrot.addFood('fruits');

lion.willEat('fruits'); //false
lion.willEat('meat'); //true
parrot.willEat('fruits'); //true

lion._gender // 'male'

//Unfortunately, JavaScript doesn't easily support "private" properties
//in objects. The _gender property we created is publicly readable and
//writable. By convention, we prefix "private" properties and functions
//with and underscore to indicate them as such.

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.

JavaScript
//Extend the Animal type to create the Human type

var Human = Animal.$extend({

    //Constructor for the Human type
    initialize: function (name, gender) {

        //Notice the call to the parent constructor below. uber behaves just like
        //super and base in Java and C#. This line will call the parent's
        //initialize function and pass gender to it.
        this.uber('initialize', gender);

        this._name = name;

        //These functions were defined in the Animal type
        this.addFood('meat');
        this.addFood('vegetables');
        this.addFood('fruits');
    },
    goVegan: function () {
        this.removeFood('meat');
    },

    //Returns something like "Mr. Crockford"
    nameWithTitle: function () {
        return this._getTitlePrefix() + this._name;
    },

    //This function is publicly accessible, but we prefix it with an underscore
    //to mark it as private/protected
    _getTitlePrefix: function () {
        if (this.getGender() === 'male') return 'Mr. ';
        else return 'Ms. ';
    }
});

The new Human class can be used as follows:

JavaScript
var jack = new Human('Jack', 'male');
var jill = new Human('Jill', 'female');
jill.goVegan();
jill.nameWithTitle() + ' eats meat? ' + jill.willEat('meat'); // Ms. Jill eats meat? false
jack.nameWithTitle() + ' eats meat? ' + jack.willEat('meat'); // Mr. Jack eats meat? true

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:

JavaScript
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'); // Domestic cat eats orijen? true
'What does the domestic cat say? ' + kitty.speak(); // What does the domestic cat say? purrr, meow!
'What does the wild cat say? ' + tiger.speak(); // What does the wild cat say? purr, growl, snarl!

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.

License

This article, along with any associated source code and files, is licensed under The BSD License