Introduction

A class is defined using the function Class to which an object is passed that contains the body. The body of a class is created using native JavaScript object notation.

A class may contain its own properties and functions (called methods) between the curly braces.

Example #1: Simple Class definition

var SimpleClass = Class({

    // property declaration
    val : 'a default value',

    // method declaration
    displayVal : function() {
        console.log(this.val);
    }
});

The psuedo-variable this is a reference to the object context of an instantiated class, allowing you to access its members (properties and methods).

The native JavaScript equivalent of the first example looks like this:

var SimpleClass = function() {
    // property declaration
    this.val = 'a default value';
}

// method declaration
SimpleClass.prototype.displayVal = function() {
    console.log(this.val);
}

The disadvantage of prototype-based classes is that it's easy to lose track of available properties and methods. This is mainly because members of the class are declared outside the 'scope' of the class body.

Creating objects

A common mistake in JavaScript is when functions designed to be classes are executed like functions. The reason for this is that both types are declared using the function keyword.

A class written using JOII can only be instantiated using the new keyword.

Example #2: Instantiating a class

// Create an object based on the class 'SimpleClass'.
var my_class = new SimpleClass();

// Write the value of 'this.val' to the console.
my_class.displayVal();

Constructor

I some cases, it's required to execute some code when a class is being instantiated. This is done using a constructor. In Java, the constructor is a method inside the class body that has the same name as the class itself. Unfortunately, this isn't possible in JavaScript. To tackle this issue, we use a method called __construct (similar to PHP).

Example #3: Using a constructor

var MyClass = Class({
    val: 'a default value',

    __construct : function(value) {
        // Assign the given 'value' to the 'val' property.
        this.val = value;
    },

    displayVal : function() {
        console.log(this.val);
    }
});

// Create an object based on MyClass and pass it a string argument.
var my_class = new MyClass('A custom value!');

// Print "A custom value!" to the console.
my_class.displayVal();

// Create another object
var second_class = new MyClass('Another value!');

// Print "Another value!" to the console.
second_class.displayVal();