Custom JavaScript classes and packages using goog.provide() and goog.require()

I will repeat it until the dead, the real power of Goolge Closure is the mechanism and the tools behind it, not the classes and methods written for you, but the possibility to write your own better JavaScript code! Today I’m gonna show you how to create and use your custom JavaScript classes and to take the benefits of goog.provide() and goog.require() methods.
Ok, let’s suppose we are working on a funny and exciting project, like an online JavaScript game called “Js Monsters Battle” and let’s suppose the domain will be www.jsmonstersbattle.com. We love OOP, we love write js code, we love to have a well organized and document code, so we will begin by creating our packages, following the standard which establishes that the root of a package must be the reversed domain name, so in our example we will create this folders structure “/com/jsmonstersbattle/” and inside we will put our classes (and subpackages).
Since our game is a game about monsters, we will create the core package “monsters” in that directory and we will write the first base class called Monster. We will got the following: “/com/jsmonstersbattle/monsters/monster.js”, three folders and one js file. Yes, one JavaScript file for class, forget those huge files containing millions of functions, we are going to write better JavaScript code and thinking more like a Java developer. If you are concerning about file size and performances, don’t worry about it, the compiler will reduce and optimize the code for you (just before release the project). Ok, let’s take a look inside the Monster class (monster.js):

goog.provide('com.jsmonstersbattle.monsters.Monster');

/**
 * A common Monster
 * @constructor
 * @param {String} name
 * @param {String} age
 * @param {Number} level
 */
com.jsmonstersbattle.monsters.Monster = function(name, age, level) {

    /** @private */ this._name = name;
    /** @private */ this._age = age;
    /** @private */ this._level = level;

}

/**
* Returns an amount of damage points
* @return {Number}
*/
com.jsmonstersbattle.monsters.Monster.prototype.attack = function() {

    return Math.round(this._level + this._age / 100) * 2000;

}

In the code above I defined a basic class called Monster, which is available under the package (namespace) com.jsmonstersbattle.monsters, declared using goog.provide(), then I created a constructor (by using the special jsDoc notation /** @constructor */) which receives three arguments and sets three private Monster’s variable (/** @private */), finally I defined a method attack which returns a number of damage points. Ok, by following the Monster’s example, we can now create as many classes and packages as we like, interfaces (using /** @interface */ and /** @impements */) and subcalsses (using the method goog.inherits()), let’s see briefly these implementation:

Extending a class:

/**
* @constructor
* @extends com.jsmonstersbattle.monsters.Monster
*/
com.jsmonstersbattle.monsters.UglyMonster = function(name, age, level, uglyness) {

    // call to Super
    com.jsmonstersbattle.monsters.Monster.call(this, name, age, level);

    /** @private */ this._uglyness = uglyness;

};

// you can read the following as: "UglyMonster extends Monster"
goog.inherits(com.jsmonstersbattle.monsters.UglyMonster, com.jsmonstersbattle.monsters.Monster);

Creating and implementing an interface:

/**
 * Evil interface.
 * @interface
 */
function IEvil() {};
IEvil.prototype.doEvil = function() {};

/**
* @constructor
* @implements {IEvil}
*/
com.jsmonstersbattle.monsters.EvilMonster = function(name, age, level) {
    // some code here
};

com.jsmonstersbattle.monsters.EvilMonster.prototype.doEvil = function() {
    // IEvil implementation
}

Once we created all the necessary classes, we will put our “com” folder under “closure” folder. Then we will create a main js file which will includes all the code required to initialize and run the application, I called it “application.js” for convenience. This file will requires all the classes it needs by using goog.require():

goog.require('com.jsmonstersbattle.monsters.EvilMonster');
// ...and so on!

After the import we will be able to use the classes, by referring them with the full qualified class name (“com.jsmonstersbattle.monsters.EvilMonster”), however since this means to write long strings, we can create references as the following:

goog.require('com.jsmonstersbattle.monsters.EvilMonster');

var EvilMonster = com.jsmonstersbattle.monsters.EvilMonster;

// then...

var monster = new EvilMonster();

or use the JavaScript with operator:

goog.require('com.jsmonstersbattle.monsters.EvilMonster');

with (com.jsmonstersbattle.monsters) {

    var monster = new EvilMonster();

}

…and this is all today, I hope you enjoyed my post ;^)

UPDATE:
Don’t use the with operator nor take reference to fully qualified class name, otherwise you will get several errors if you use advanced compilation!

  • chrismarx

    in order to get this to work, I also needed to add a call to goog.addDependency in the deps.js — did I do something wrong, or did you omit this detail?

  • you are right chris, but if you use calcdeps.py, you don’t have to care about goog.addDependency calls, these will be automatically handled by the tool ;^)