Brian Koponen

Programming and Tech Tips

JavaScript Classes Quick Reference

JavaScript has no concept of classes built in, but you can essentially create classes quite easily because of the looseness of JavaScript. This is basically a cheat sheet for the common class paradigms in JavaScript.

Class Construction

function ClassA (parameter1) {
    this.instanceVariable = parameter1;
}

ClassA.prototype.methodName = function (p1) {
};

var instance = new ClassA( "param" );
instance.methodName( "param" );


Inheritance

function SubclassA (parameter1) {
    ClassA.call(this);

    this.instanceVariable = parameter1;
}
SubclassA.prototype = Object.create(ClassA.prototype);

SubclassA.prototype.subclassMethod = function () {
};

var subclassInstance = new SubclassA( "param" );
subclassInstance.methodName( "param" );
subclassInstance.subclassMethod();

Method Override

SubclassA.prototype.methodName = function (p1) {
    ClassA.prototype.methodName.call(this, p1);
};


Singleton

var singleton = (function () {
    var _privateVariable1,
        _privateVariable2;

    function _privateMethod () {

    }

    function _publicMethodImplementation () {

    }

    return {
        publicGetter: function () { return _privateVariable1; },
        publicMethod: _publicMethodImplementation
    };
})();

var a = singleton.publicGetter();
singleton.publicMethod();


Type Identification

var a = new ClassA ();
var b = new SubclassA ();

a instanceof ClassA;    // returns true
a instanceof SubclassA; // returns false
b instanceof ClassA;    // returns true
b instanceof SubclassA; // returns true

Question or Comment?